Accepted Solution in Java


  • 0
    R
        public int reverse(int x) { 
            LinkedList<Integer> st = new LinkedList<Integer>() ;
            boolean positive = (x > 0 ? true : false) ;
            while ( (!positive && x < -9) || (positive && x > 9) ) {
                // System.out.println("In: " + x%10) ;
                st.offer ( x % 10 ) ;
                x /= 10 ;
            }
            // System.out.println("In: " + x) ;
            st.offer(x) ;
            
            long i = 1 ; 
            long s = 0 ;
            while (st.size() != 0) {
                long p = st.pollLast() * i;
                s += p ;
                // System.out.println( " p: " + p + " s: " + s + " Max: " + Integer.MAX_VALUE + " Min: " + Integer.MIN_VALUE) ;
                if ( s > Integer.MAX_VALUE || s < Integer.MIN_VALUE ){
                    s = 0;
                    break;
                } 
                i *= 10 ;
            }
            
            return (int)s;
        }
    

Log in to reply
 

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