Solution by coderGirl


  • 0
    C

    Approach #1 One pass solution [Accepted]

    Algorithm

    In this algorithm we are following the usual method of reversing an integer. That is extract the digit from the end, multiplying it by 10 and then adding it to the answer.
    Some extra steps are to be followed for this question.

    1. First we need to take care of the sign of the number
    2. We need to take care of the overflow condition
      The following check does exactly that:
    if((newResult-remainder)/10!=result) {
        return 0;
    }
    

    Note: Mod 10 extracts a digit from the end of the number and / by 10 extracts a digit from the beginning of the number

    Java

    public class Solution {
        public static int reverse(int x) {
            int sign=1;
            if(x<0) {
                sign = -1;
                x=Math.abs(x);
            }
            int newResult=0,result=0;
            //reversing an integer
            while(x>0)
            {
                int remainder=x%10;
                newResult=result*10+remainder;
                if((newResult-remainder)/10!=result) {
                    return 0;
                }
                result=newResult;
                x=x/10;
            }
            return newResult*sign;
        }
    

    Complexity Analysis

    • Time complexity : O(n).
      Since we are extracting every digit one by one and only one for loop is used the complexity will be O(n)

Log in to reply
 

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