[Question:]
Reverse digits of an integer. EXAMPLE1:X = 123, return 321
example2:x = -123, return-321
Solving: Given an integer, the number of this integer is rotated position.
[Analysis:] Here are some good the questions to ask before coding. Bonus points for/If you have already thought through this!
If the digit is 0, what should the output to be? ie, cases such as 10, 100.
More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/
Did you notice the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should do you handle such cases?
Throw an exception? Good, but what if throwing a exception is isn't an option? You are would then have to re-design the function (ie, add a extra parameter). Note Point 1: If the last digit of an integer is 0, such as: 10100, then the inversion will turn into 101. NOTE 2: If you enter a number of 1000000003, then the reversal will overflow, you need to pay attention.
[Solution:]
*
* Assume the input 123:
* 123-> 3
*-> + 2
* 1-> + 1 *
* Public
class Solution {
pub LIC int reverse (int x) {
int = 0;
while (x!= 0) {Results
= result * + x% 10;//each time on the basis of the original results to 10 times times larger, plus the remainder
x = X/10;
Eturn 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));}}