Solution by coderGirl

  • 0

    Approach #1 One pass solution [Accepted]


    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


    public class Solution {
        public static int reverse(int x) {
            int sign=1;
            if(x<0) {
                sign = -1;
            int newResult=0,result=0;
            //reversing an integer
                int remainder=x%10;
                if((newResult-remainder)/10!=result) {
                    return 0;
            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.