leetcode-7:Reverse Integer

来源:互联网 发布:上海淘宝公司招人 编辑:程序博客网 时间:2024/06/10 04:05

很简单的题目,思路:
x = a1a2a3a4a5a6….an
则得到的反转数字为
result = an*10^n + a(n-1) * 10^(n-1) + …….a1 = (((an*10+a(n-1))*10 + a(n-2))*10…….) + a1
1.初始化对应变量和常量;
2.对10求余得到当前循环中原数的低位,把临时的结果乘10并加上该低位作为新的临时结果,不断循环该步骤,直到溢出或者已经遍历所有数位;
3.返回结果;
源码:

class Solution {public:    int reverse(int x) {        int highestHead = 214748364;        int highestTail = 7;        int locs = 10;        int lowHead = -214748364;        int lowTail = -8;        int divided = x;        int result = 0;        int locsNum = 0;        int temp = 0;        int flag = divided>0? 1 : 0;        int head= 0;        while(divided!=0){            locsNum++;            temp = divided%10;            if(locsNum>=locs){                if(flag && (result>highestHead || (result == highestHead  && temp >highestTail)) ) return 0;                if(flag==0 && (result < lowHead || (result == lowHead  && temp <lowTail)))  return 0;            }            result = result * 10 + temp;            divided /= 10;        }        return result;    }};
原创粉丝点击