LeetCode 007 Reverse Integer

来源:互联网 发布:json时间格式化 编辑:程序博客网 时间:2024/06/11 06:50

简单题,不过需要判断是否逆转后的数字超过int的范围,int的范围为-(1<<31)到(1<<31)-1。

class Solution {public:    int reverse(int x) {        int s[1000];        int cnt=0;        int mark=1;        long long sum=1;        long long ans=0;        if(x<0){mark=-1;x*=mark;}        while(x){            s[cnt++]=x%10;            x/=10;        }        while(cnt){            ans+=s[--cnt]*sum;            sum*=10;        }        if(ans>2147483647||ans<-2147483648)return 0;        return ans*mark;    }};


0 0