C++ solution for reverse integer with no overflow handling. complexity - log(n)


  • 0
    G
    int reverse_integer(int x)
    {
    	int result = 0;
    	int negative_flag = 1;
    	int reminder = 0;
    	negative_flag = x < 0 ? x = -x, -1 : 1;
    	do
    	{
    		reminder = x % 10;
    		result = reminder + 10* result;
    		x /= 10;
    	} while (x > 0);
    	return result*negative_flag;
    }

  • 0
    L

    class Solution {
    public:
    int reverse(int x)
    {
    if(x >-10 && x < 10) return x;

        int iRet = 0;
        do
        {
            iRet= iRet *10 + x%10;
        }
        while(x/=10);
        return iRet;
    }
    

    };

    it is ok either.not need negative_flag


  • 0
    L
    int reverse(int x) 
    {
        if(x >-10  && x < 10) return x;
        int d = x;
        int i = 1;
        
        while(d/10)
        {
            i *=10;
            d /=10;
        }
        
        int iRet = 0;
        while(x)
        {
            iRet += (x %10)*i;
            x /= 10;
            i /= 10;
        }
        return iRet;
    }
    

    and this is faster on testing...wow


Log in to reply
 

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