Friday, May 5, 2017

LeetCode 2nd time 7. Reverse Integer Leetcode Java

     public int reverse(int x) {  
    if(x==0 || x==Integer.MIN_VALUE) return 0;  
    boolean neg=(x<0);  
    int res=0;  
    x=Math.abs(x);  
    while(x !=0){  
      if(neg){  
        if((Integer.MIN_VALUE+(x%10))/10>res) return 0;  
        else res=res*10-x%10;  
      }  
      else{  
        if((Integer.MAX_VALUE-(x%10))/10<res) return 0;  
        else res=res*10+x%10;  
      }  
      x=x/10;  
    }  
    return res;  
   }  

No comments:

Post a Comment