Can I improve this?


  • 0

    I think my algorithm may not that efficient, is there a way to improve it?

    int reverse(int a) 
        {
            int testNum;
        	int digit;
        	string number;
        	if (a < 0)
        	{
        		testNum = -a;
        	}
        	else
        	{
        		testNum = a;
        	}
        	int index = 0;
        	while (testNum != 0)
        	{
        		digit = testNum % 10;
        		if (digit != 0 || number.size())
        		{
        			number += ('0' + digit);
        			index++;
        		}
        		testNum /= 10;
        	}
        	int result = atoi(number.c_str());
        	if (a < 0)
        	{
        		result = -result;
        	}
        	return result;    
        }

  • 0
    K

    The complexity of above solution is log(n). So the algorithm is quite efficient and no algorithm exist to reverse a number which is more efficient than log (n). But there are few problem in your solution.
    (1) You are not checking the overflow and underflow. (2) It can be done without using extra memory i.e without using the string.


Log in to reply
 

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