在Java中,可以使用下面提到的方法来求出给定整数的倒数。
方法一:使用迭代
该方法涉及以下步骤:
Input: MyNum
Step 1: Initialize the RevNum = 0
Step 2: Iterate over MyNum while it is greater than zero.
Step 2a: Calculate remainder of MuNum / 10
Step 2b: Update RevNum by RevNum * 10 + remainder
Step 2c: Update MyNum by MyNum / 10
Step 3: Return RevNum
示例:
Input: 564
RevNum: 0
Iteration 1:
Remainder: 564 % 10 = 4
RevNum: 0 * 10 + 4 = 4
MyNum: 564 / 10 = 56
Iteration 2:
Remainder: 56 % 10 = 6
RevNum: 4 * 10 + 6 = 46
MyNum: 56 / 10 = 5
Iteration 3:
Remainder: 5 % 10 = 5
RevNum: 46 * 10 + 5 = 465
MyNum: 5 / 10 = 0
return RevNum = 465
下面的代码块显示了上述概念的实现:
public class MyClass {
static int reverse(int MyNum) {
int RevNum = 0;
int remainder;
while(MyNum > 0){
remainder = MyNum % 10;
MyNum = MyNum / 10;
RevNum = RevNum * 10 + remainder;
}
return RevNum;
}
public static void main(String[] args) {
int x = 1285;
int y = 4567;
System.out.println("Reverse of " + x + " is: " + reverse(x));
System.out.println("Reverse of " + y + " is: " + reverse(y));
}
}
上面的代码将给出输出如下:
Reverse of 1285 is: 5821
Reverse of 4567 is: 7654
方法2:使用递归
使用递归方法也可以实现上述结果。考虑下面的示例:
public class MyClass {
static int RevNum = 0;
static int base = 1;
static int reverse(int MyNum) {
if(MyNum > 0){
reverse(MyNum/10);
RevNum += MyNum % 10 * base;
base *= 10;
}
return RevNum;
}
public static void main(String[] args) {
int x = 7902;
System.out.println("Reverse of " + x + " is: " + reverse(x));
}
}
上面的代码将给出以下输出:
Reverse of 7902 is: 2097