【leetcode】4 Reverse Ingeger

Reverse digits of an integer.

Example1: x =  123, return  321

Example2: x = -123, return -321

注意:1 溢出

   2 多用三目表达式

     3 逆置处理:(先算位数,再求,比较麻烦导致超时;直接在上次计算基础上rest*10,及自动移位)

class Solution {
public:
    int reverse(int x) {
        long long rest=0,y=x;
        int sig=1;
        
        if(x<0)
           sig=-1;
        y=y>0?y:-y;//后面的3个y不能用x替换
            
        while(y!=0){
            rest=rest*10+y%10;//逆置处理
            y=y/10;
        }
        if(rest >= 2147483647)  
              return 0;//溢出
        else
            return  sig*rest;
       
    }
};

 

原文地址:https://www.cnblogs.com/wygyxrssxz/p/4492395.html