Tricky Addition

Kefa loves large numbers. He has recently learned the addition of two large numbers and is practicing sums to master it.

The next day, the teacher in the class plays a trick with the students. He says to solve the questions but without following the conventional addition approach.

He tells them to give the leftmost digit of each number highest preference and start the addition of the numbers from the left-hand side and take the carrier to the next digit to the right (refer to the explanation given below for further clarification).

Kefa is unfortunately confused about how to tackle this problem. Help him to crack this one!

Example:

Input:  n = 26,  m = 9
Output: 17

Approach

C++

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

string trickyAddition(long long nlong long m)
{

    vector<long longab;
    while (n)
    {
        a.push_back(n % 10);
        n = n / 10;
    }
    while (m)
    {
        b.push_back(m % 10);
        m = m / 10;
    }
    long long carry = 0;
    n = a.size();
    m = b.size();
    string ans = "";

    long long i = n - 1j = m - 1;
    while (i >= 0 || j >= 0)
    {
        if (i >= 0 && j >= 0)
        {
            long long x = a[i] + b[j] + carry;
            long long y = x;
            if (x >= 10)
            {
                carry = x % 10;
                x = x / 10;
            }
            else
                carry = 0;
            ans += to_string(x);
            if (i == 0 && j == 0 && y >= 10)
            {
                ans += to_string(y % 10);
                carry = 0;
            }
            i--;
            j--;
        }
        else if (i >= 0)
        {
            long long x = a[i] + carry;
            int y = x;
            if (x >= 10)
            {
                carry = x % 10;
                x = x / 10;
            }
            else
                carry = 0;
            ans += to_string(x);
            if (i == 0 && y >= 10)
            {
                ans += to_string(y % 10);
                carry = 0;
            }
            i--;
        }
        else if (j >= 0)
        {
            long long x = b[j] + carry;
            int y = x;
            if (x >= 10)
            {
                carry = x % 10;
                x = x / 10;
            }
            else
                carry = 0;
            ans += to_string(x);
            if (j == 0 && y >= 10)
            {
                ans += to_string(y % 10);
                carry = 0;
            }
            j--;
        }
    }
    if (carry > 0)
        ans += to_string(carry);
    return ans;
}
int main()
{

    long long n = 26m = 9;

    cout << trickyAddition(nm<< "\n";

    return 0;
}


No comments:

Post a Comment