DarkSnake
DarkSnake

Reputation: 59

Need to split an integer and add it with itself

So, my basic problem is that I'm trying to write a program for a small project I'm working on for fun.

Basically, my issue is this: I need to take user input, as an int, say 15, then manipulate the number so that it returns the result of 1 + 5, being 6. Or for another example say the number is 29, will give you 2 + 9 = 11, which would then need to be reduced down again to 1 + 1 = 2. That could probably be handled easily, but I'm stuck on how to actually split the int apart without having to take the numbers in one by one. I guess it's possible to with RegEx, but I was looking for a more efficient method.

Upvotes: 0

Views: 476

Answers (4)

Pablo Venturino
Pablo Venturino

Reputation: 5318

I think the quickest way here is to use / (divide) and % (modulus) operators to traverse your integer.

int base = 15;
int acum = 0;
while (base > 0) {
    acum = acum + (base % 10);
    base = base / 10;
};

// At this point, base = 0 and acum = 6
// if acum > 10, then assign it to base and start again.

Upvotes: 0

Eelvex
Eelvex

Reputation: 9133

In C, this would do the trick for two digits:

digit_sum = my_int%10 + my_int/10

Upvotes: 0

Asha
Asha

Reputation: 11232

A sample code is here:

int sum_of_digits(int n)
{
    if(n < 10)
    {
        return n;
    }

    int sum = 0;
    while( n > 0)
    {
        sum += n % 10;
        n /= 10;
    }
    return sum_of_digits(sum);
}

int main()
{
    int n1 = sum_of_digits(29);
    int n2 = sum_of_digits(15);
}

Upvotes: 2

Jerry Coffin
Jerry Coffin

Reputation: 490138

This is not a particularly good job for a regex. The usual way would be to get individual digits as the remainder after dividing by 10.

Upvotes: 4

Related Questions