Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

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?

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).

 

思路:反向求字符串的值 ;但该题目中一个问题,如果输入是-2147483648,则如果反过来,则很定会溢出的。 

java代码:用long 64位表示较好,注意在C++中long和int一样,都是32位的,需要用long long表示

  1. public int reverse(int x) {
  2. long start = x;
  3. boolean sign = x > 0 ? true : false;
  4. if(!sign) start = -x;
  5. long base = 0;
  6. while(start!=0) {
  7. base = base * 10 + start%10;
  8. start = start/10;
  9. }
  10. if(!sign) return (int)-base;
  11. else
  12. return (int)base;
  13. }
posted @ 2014-07-28 19:06  purejade  阅读(75)  评论(0编辑  收藏  举报