StringBuilder and BigInteger Solution (Straight Forward) Java


  • 0
    E

    I see a lot of people using math and modulo, etc. It is easy to make a mistake on a whiteboard.

    import java.math.*;
    public class Solution {
        public int reverse(int x) {
            if(x == 0) return 0;
            BigInteger max = BigInteger.valueOf(Integer.MAX_VALUE);
            BigInteger min = BigInteger.valueOf(Integer.MIN_VALUE);
            StringBuilder sb = new StringBuilder(x + "");
            boolean isNegative = x < 0 ? true : false;
            
            if(isNegative){
              sb.deleteCharAt(0);
              sb.append('-');
            }
            sb.reverse();
            sb = sb.charAt(0) == '0' ? removeLeadingZeros(sb) : sb;        
            BigInteger num = new BigInteger(sb.toString());
           
            if(num.compareTo(max) > 0 || num.compareTo(min) < 0 ) return 0;
            return Integer.parseInt(sb.toString());
        }
        private StringBuilder removeLeadingZeros(StringBuilder sb){
            int index = 0;
            while(sb.charAt(index) == '0') sb.deleteCharAt(index);
            return sb;
        }
    }

Log in to reply
 

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