leetcode reverse Integer(反转整数)
2017-05-17 16:49
423 查看
原题:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
反转一个整数,反转的过程不难,关键要注意几点
1. 当一个数字末尾为0时,反转后应该去掉。比如:1200000 反转后为 21.
2. 当一个整数超大不越界,但是反转后却越界了 比如:1000000003 反转成 3000000001 溢出(整数范围为 -2147483648
到 2147483647)
总体思路就是,首先去除后面的0。然后统计余下数字的位数(按指数统计 1位数字计为1,2位数字计为10,3位数字计为100,方便后面计算)。
之后从低位开始累加,最终得到结果
举例说明: 12300,先去除末位的00,得到123,在统计位数(由于是3位,则位数统计为 numPow = 100),让123
/ 100 得到 1
sum+=1; 更新数字123(由于1已经加入sum,123 - 100 = 23) 此时的num 由123 -> 23,位数由100 -> 10,然后重复执行该过程,直到num = 0为止
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
反转一个整数,反转的过程不难,关键要注意几点
1. 当一个数字末尾为0时,反转后应该去掉。比如:1200000 反转后为 21.
2. 当一个整数超大不越界,但是反转后却越界了 比如:1000000003 反转成 3000000001 溢出(整数范围为 -2147483648
到 2147483647)
总体思路就是,首先去除后面的0。然后统计余下数字的位数(按指数统计 1位数字计为1,2位数字计为10,3位数字计为100,方便后面计算)。
之后从低位开始累加,最终得到结果
举例说明: 12300,先去除末位的00,得到123,在统计位数(由于是3位,则位数统计为 numPow = 100),让123
/ 100 得到 1
sum+=1; 更新数字123(由于1已经加入sum,123 - 100 = 23) 此时的num 由123 -> 23,位数由100 -> 10,然后重复执行该过程,直到num = 0为止
public class Solution { public int reverse(int x) { long sum = 0; long num = Math.abs(x); if(num<10) return x; while(num%10 == 0)//将尾部的0去掉 num = num/10; long numPow = 1;//记录的位数 while(num/numPow>=10) numPow*=10; long digit = 1;//表示进位从1开始 while(num>0) { sum+=(num/numPow) *digit;//从低位开始加 digit*=10;//下一位乘10 num = num % numPow; numPow/=10; } sum = x<0?sum *(-1):sum; return (int)sum; } }ps:代码不一定最优,若有问题,欢迎纠错。。。
相关文章推荐
- Leetcode:Reverse Integer ,整数反转
- LeetCode--Reverse Integer(整数反转)Python
- 【leetcode】Reverse Integer整数反转----Java代码实现
- LeetCode7——Reverse Integer(将一个整数反转,注意溢出的处理)
- (LeetCode)Reverse Integer --- 反转整数
- LeetCode Reverse Integer 反转整数
- [LeetCode-7] Reverse Integer(反转整数)
- [leetcode] Reverse Integer 反转一个整数
- leetcode——Reverse Integer 反转整数数字(AC)
- 【LeetCode】- Reverse Integer(将一个整数反转)
- [leetcode 7] Reverse Integer(整数反转) c函数实现
- [Leetcode] reverse integer 反转整数
- Leetcode Reverse Integer 反转整数
- LeetCode 7 :Reverse Integer ---- 反转int整数
- [置顶] [LeetCode] Reverse Integer 整数反转
- [Leetcode #7]Reverse Integer整数反转、逆向打印整数
- LeetCode 7 Reverse Integer(反转数字)
- [Leetcode #7]Reverse Integer整数反转、逆向打印整数
- LeetCode 7. Reverse Integer 整数反转
- Leet Code 7 Reverse Integer - 整数反转 - Java