Reverse digits of an integer. java
Example1: x = 123, return 321
Example2: x = -123, return -321 git
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this! this
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100. spa
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases? code
Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter). leetcode
https://oj.leetcode.com/problems/reverse-integer/ get
思路:從低到高依次取得數字的每一位累加到新數字中。 input
public class Solution { public int reverse(int x) { int result = 0; boolean neg = false; if (x < 0) { neg = true; x = -x; } int a = 0; while (x != 0) { a = x % 10; x /= 10; result = result * 10 + a; } if (neg) result = -result; return result; } public static void main(String[] args) { System.out.println(new Solution().reverse(123)); System.out.println(new Solution().reverse(-123)); System.out.println(new Solution().reverse(1)); System.out.println(new Solution().reverse(-1)); System.out.println(new Solution().reverse(0)); } }