Adding a interger to every part of another interger

I am testing a encryption algorithm and i currently have the issue as followed;

I need to enter a integer such as 123 and then a key such as 3 and what happens is that i need to add this number 3 to each part of the "123" then resulting into "456" however I have no clue how I would tackle this any help would be great.

Note that the value of "123" and "3" above can be changed at any time, so I can't set a specific value.
what is the output if they enter 999 and 7 ?
Sorry should have elaborated on this better, if there that occurred it would then be added and then changed back to 666 as it would go to 10 and then reset and carry on the addition.
Each digit needs to be considered independently. You can isolate the last digit by using the modulus operator %. For example, 789%10 = 9. Modulus is also needed for the next part of the calculation (9+3)%10 = 2, so these can be combined to get (789+3)%10 = 2. You can use a loop and division by ten to get more digits.

These methods work because of the properties of the base 10 number system.
Last edited on
Recursion can be used here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

int f(int n, int off) {
    if (n == 0) return 0;
    int r = f(n / 10, off);
    int d = (n % 10 + off) % 10;
    return r * 10 + d;
}

int main() {
    int n, off;
    while (std::cin >> n >> off)
        std::cout << f(n, off) << '\n';
}


(How do people get the little gear at the top right of the code that lets you run it?)
Last edited on
Topic archived. No new replies allowed.