[ 問題: ]
Reverse digits of an integer. Example1: x = 123, return 321題解:給定一個整數,將這個整數的數字旋轉位置。
[ 陷阱 : ]
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
/*
* 假設輸入123:
* 123 -> 3
* 12 -> 30 + 2
* 1 -> 320 + 1
*/
public class Solution {
public int reverse(int x) {
int result = 0;
while (x != 0) {
result = result * 10 + x % 10; // 每一次都在原來結果的基礎上變大10倍,再加上余數
x = x / 10; // 對x不停除10
}
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(new BufferedInputStream(System.in));
while (scanner.hasNext()) {
int num = scanner.nextInt();
System.out.println(new Solution().reverse(num));
}
}
}