题解 | #反转数字#

反转数字

http://www.nowcoder.com/practice/1a3de8b83d12437aa05694b90e02f47a

使用技巧把负数情况变成正数,越界的判断;

如果当前的数比大214748364/10并且还有一位就会越界

import java.util.*;

public class Solution {

    public int reverse (int x) {
        // write code here
        int ans = 0;
        int flag = 1;
        
        if(x<0){
           flag = -1;
           x = -x;
        }
        
        while(x>0){
            int t = x%10;
            ans=ans*10+t;
            x/=10;
            if((ans>Integer.MAX_VALUE/10+1&&x>0)return 0;
        }
        return ans*flag;
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务