Strange addition

HackerMan has a message that he has coded in form of digits, which means that the message contains only numbers and nothing else. He is fearful that the enemy may get their hands on the secret message and may decode it. HackerMan already knows the message by heart and he can simply destroy it.

But he wants to keep it in case it's needed in a worse situation. He wants to further encode the message in such a format that is not completely reversible. This way if enemies get hold of the message they will not be completely able to decode the message.

Since the message consists only of numbers he decides to flip the numbers. The first digit becomes last and vice versa. For example, if there is 3769 in the code, it becomes 9673 now. All the leading zeros are omitted e.g. 15900 gives 951. So this way the encoding can not completely be deciphered and has some loss of information.

HackerMan is further thinking of complicating the process and he needs your help. He decides to add the two flipped numbers and print the result in the encoded (flipped) form. There is one problem in this method though. For example, 134 could be 4314310 or 43100 before reversing. Hence the method ensures that no zeros were lost, that is it can be assumed that the original number was 431.

Example:

Input:  n = 353, m = 575
Output: 829

Approach

C++

#include <bits/stdc++.h>
using namespace std;

long long reverse(long long n)
{
    long long res = 0;
    long long x = 10;
    while (n)
    {
        res = res * x + n % 10;
        n = n / 10;
    }
    return res;
}

long long strangeAddition(long long n,
                          long long m)
{
    long long x = reverse(n);
    long long y = reverse(m);
    long long ans = x + y;
    ans = reverse(ans);
    return ans;
}
int main()
{

    long long n = 353;
    long long m = 575;

    cout << strangeAddition(n, m) << "\n";

    return 0;
}


No comments:

Post a Comment