Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
解答如下:
class Solution { public int reverse(int x) { int sumold=0,sumnew=0; while(x!=0) { sumnew=sumold*10+x%10; if(sumold>Integer.MAX_VALUE/10||sumold<Integer.MIN_VALUE/10) return 0; else sumold=sumnew; x/=10; } return sumnew; } }
1、正数与负数处理方法相同;
2、溢出验证是对sumold进行操作,保证可以算到最后一位;
3、如果sumold比Integer.MAX_VALUE/10大,则它乘以10再加一个值必定溢出,负方向的溢出原理相同;(这里其实有一定误差)
时间: 2024-11-08 22:17:30