Solution for Reverse Integer in Java


  • 0
    R

    class Solution {
    public int reverse(int x) {

            boolean isNegative=false;
            if(x<0){
                isNegative=true;
                x=Math.abs(x);
            }
            int[] noArray=getReversedDigitArray(x);
            int pow=noArray[0]-1;
            double no=0;
            for(int i=1;i<=noArray[0];i++) {
                no=no+(noArray[i]*(Math.pow(10,pow)));
                if(no>2147483647) {
                    return 0;
                }
                pow--;
            }
            if(isNegative){
                no=no*-1;
            }
            return (int) no;
    
    }
    
        private int[] getReversedDigitArray(int no) {
            int[] noArray = new int[100];
            int index=1;
            boolean startRecord=false;
            while(no>0) {
                int digit=no%10;
                if (!startRecord && digit>0) {
                    startRecord=true;
                }
                if(startRecord){
                    noArray[index]=digit;
                    index++;
                }
                no=no/10;
            }
            noArray[0]=--index;
            return noArray;
        }
    

    }


Log in to reply
 

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