Reverse integer solution in Java


  • 0
    E

    class Solution {
    public int reverse(int x) {

        if ( x==0 ) {
            
            return 0;
        }
            
        int r = reverseInt(x);
        int r2 = reverseInt(r);
        
        while (x % 10 == 0) {
            
            x /= 10;
        }
        
        if ( x != r2 ) {
            
            return 0;
        }
        
        return r;
    }
    
    public int reverseInt(int x)  {
        
        List<Integer> list = new ArrayList<Integer>();
        
        while (x != 0) {
            
            list.add(x % 10);
            x /= 10;    
        }
        
        int sum = 0;
        for ( int i = list.size() - 1, j = 1 ; i >=0 ; --i, j *= 10) {
            
            sum += (list.get(i) * j);
        }
        
        return sum;
    }
    

    }


Log in to reply
 

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