reverse integer in Java


  • 0
    Z
    class Solution {
        public int reverse(int x) {
            int flag = x>0 ? 1:-1;
            int result = 0;
            x = Math.abs(x);
            while(x>0){
                int temp = 10 * result + x%10;
                x = x/10;
                if(temp/10 != result){ //avoid overflow
                    result = 0;
                    break;
                }
                result = temp;
            }
            result = flag * result;
            return result;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.