输入:
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 :(得分:0)
试试这个。
public static void reverseMethod(int number) {
if (number < 10) {
System.out.println(number);
return;
}
else {
System.out.print(number % 10);
reverseMethod(number/10);
}
}
答案 1 :(得分: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);
}
}
答案 2 :(得分:0)
找到比最小数字小10的最大功率,并用它来反转数字。这允许您“将数字移动到正确的位置”:
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));
}
答案 3 :(得分: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);
}
答案 4 :(得分: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);
}
}