2016-06-18 57 views
0

輸入的總和:遞歸 - 如何可以單獨打印每一個數字,而不是數量

123 

輸出:

6 >>> (It is the sum of all digits) 

我想輸出將:

321 

這意味着每個數字分開

代碼中出現了什麼問題?

代碼:

public class t4 { 
public static void main(String[] args) { 
    System.out.println(ReverseNum(123)); 
} 

public static int ReverseNum(int num) { 
    int dig = 0; 
    if (num == 0) 
     return dig; 

    dig = dig * 10 + num % 10; 

    return ReverseNum(num/10) + dig; 

} 
} 

感謝的

+0

因此,所有你要的只是打印數字的反向?如果輸入是「123」,並且你希望輸出反向「321」。是嗎 ? –

+0

是否有任何具體的要求,你需要去遞歸? –

+0

public static String ReverseNum(int num){ \t \t String dig =「」; \t \t if(num == 0)return dig; \t \t dig = Integer.toString(num%10); \t \t return dig + ReverseNum(num/10); } –

回答

0

試試這個。

public static void reverseMethod(int number) { 
    if (number < 10) { 
     System.out.println(number); 
     return; 
    } 
    else { 
     System.out.print(number % 10); 
     reverseMethod(number/10); 
    } 
} 
0

你可以試試:

public class t4 { 
public static void main(String[] args) { 
    System.out.println(ReverseNum(123)); 
} 

public static String ReverseNum(int num) { 
    if (num == 0) 
     return ""; 


    return "" + num % 10 + ReverseNum(num/10); 

} 
} 
0

先找到十個最大功率比數量更小,用它來扭轉數。這使您可以「將數字移到正確的位置」:

public static int findPow10(int num) { 
    if (num < 10) { 
     return 1; 
    } else { 
     return 10 * findPow10(num/10); 
    } 
} 

private static int reverseHelper(int num, int factor) { 
    if (num == 0) { 
     return 0; 
    } else { 
     return factor * (num % 10) + reverseHelper(num/10, factor/10); 
    } 
} 

public static int reverse(int num) { 
    return reverseHelper(num, findPow10(num)); 
} 

public static void main(String[] args) { 
    System.out.println(reverse(123)); 
} 
0

而不是打印值,我試圖返回數字。這是我迄今爲止所能想到的。我認爲別人可能會做得更好。這裏面的while循環並不是那麼優雅。

public static int ReverseNum(int num) { 
    if (num < 10){ 
     return num; 
    } 
    int val = 1; int n = num; 
    while(n > 10){ 
     n = n/10; 
     val = val * 10; 
    } 

    return (num % 10)*val + ReverseNum((num - num % 10)/10); 
} 
0
class Solution 
{ 
    //A method for reverse 
    public static void reverseMethod(int number) 
    { 
     if (number < 10) 
     { 
     System.out.println(number); 
     } 
     else { 
      System.out.print(number % 10); // 123 % 10 = 3 
      //Method is calling itself: recursion 
      reverseMethod(number/10); //123/10 = 12 integer ignore decimal number 
      } 
    } 
    public static void main(String args[]) 
    { 
    reverseMethod(123); 

    } 
}