My Accept version to this problem in c++


  • 0
    J
    class Solution {
    int dig[15];
    int re;
    public:
    int reverse(int x) {
    	int xx=abs(x);
    	int j=14;
    	while(xx/10)
    	{
    		int a=xx%10;
    		dig[j]=a;
    		xx=xx/10;
    		j--;
    
    	}
    	dig[j]=xx%10;
    	int i=14;
    	while(dig[i]==0)
    	{
    		i--;
    	}
    	int k=0;
    	re=0;
    	for(;j<=i;j++)
    	{
    		re+=dig[j]*pow(10.0,k);
    		k++;
    	}
    
    	if(x<0)
    		re=-re;
    
    	return re;
    }
    };

  • 0
    S

    Thanks for your post. However it would be better to share solution with correct code format and elaborated thoughts. Please read the Discuss FAQ for more info. Take a look at good sharing example


  • 1
    N

    mine a shorter one? there must be better solutions than mine.

    class Solution {
    public:
        int reverse(int x) {
            long y = 0;
            int m = x;
            x = abs(x);
            while(x != 0)
            {
                y = y * 10 + x % 10;
                x = x / 10;
            }
            if(m < 0)
                return -y;
            else
                return y;
        }
    };

  • 0
    H

    Thank you for posting your code. This algorithm is brief than mine.


Log in to reply
 

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