Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I keep only non-zero digits from an integer?

Tags:

c++

I am currently using the code below that removes all digits equal to zero from an integer.

int removeZeros(int candid)
{
     int output = 0;
     string s(itoa(candid));
     for (int i = s.size(); i != 0; --i)
     {
         if (s[i] != '0') output = output * 10 + atoi(s[i]);
     }
     return output;
}

The expected output for e.g. 102304 would be 1234.

Is there a more compact way of doing this by directly working on the integer, that is, not string representation? Is it actually going to be faster?

like image 379
janejoj Avatar asked Nov 29 '15 10:11

janejoj


1 Answers

Here's a way to do it without strings and buffers.

I've only tested this with positive numbers. To make this work with negative numbers is an exercise left up to you.

int removeZeros(int x)
{
    int result = 0;
    int multiplier = 1;
    while (x > 0)
    {
        int digit = x % 10;
        if (digit != 0)
        {
            int val = digit * multiplier;
            result += val;
            multiplier *= 10;
        }
        x = x / 10;
    }

    return result;
}
like image 147
selbie Avatar answered Sep 21 '22 21:09

selbie