码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 7. Reverse Integer 一个整数倒叙输出

时间:2018-09-09 12:01:23      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:within   ccf   ret   问题:   fun   eal   支持   integer   nbsp   

潜在问题:(1)随着求和可能精度会溢出int 范围,需要使用long 来辅助判断是否溢出,此时返回 0

               Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [?231,  231 ? 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

               (2)去前缀0

eg: reverse(1534236469); 会丢精度,如果不校验 所以WA了一次

 

int reverse(int x) {
    long sumLong = 0;
    int sum = 0;
    int num =  0;
    while (x!= 0) {    //支持正负数
        num = x % 10;  //末尾数字
        sum = sum * 10;//进位
        sum += num;
        x = x / 10;
        //校验精度
        sumLong = sumLong * 10;
        sumLong += num;
        if (sumLong != sum) {
            sum = 0;
            break;
        }
    }
    return sum;
}

 

LeetCode 7. Reverse Integer 一个整数倒叙输出

标签:within   ccf   ret   问题:   fun   eal   支持   integer   nbsp   

原文地址:https://www.cnblogs.com/someonelikeyou/p/9611139.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!