[英]How to reverse a number using recursion
I want to send in the recursion only the number itself and not more variables!!! 我想只递归发送数字本身,而不发送更多变量!
so, I made a code that make the operation but I don't have the stop point. 因此,我编写了进行操作的代码,但没有停止点。
the code: 编码:
public static int upsideDown (int number) {
number += (number%10)*(Math.pow(10, String.valueOf(number).length()));
number %= 10;
return upsideDown (number);
}
You need to store the digit you are working with in a local variable instead of modifying number
. 您需要将要使用的数字存储在局部变量中,而不是修改
number
。
You need - instead of number %= 10
- to (integer) divide by 10 instead. 您需要-而不是
number %= 10
来(整数) 除以 10。
You need to multiply the previously stored digit by 10 raised to the power of string.length - 1
; 您需要将先前存储的数字乘以10以提高到
string.length - 1
的幂; you need to add the result of this to the return value of the recursive call to upsideDown
. 您需要将此结果添加到对
upsideDown
的递归调用的返回值中。 Actually, a for loop over length - 1
, multiplying by 10 each time through the loop would be more efficient than using pow
. 实际上,对于
length - 1
的for循环,每次通过循环乘以10会比使用pow
更有效。
Exit code should simply be if (number == 0) return 0;
退出代码应该只是
if (number == 0) return 0;
at start of method. 在方法开始时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.