ADDONE - Editorial

Prerequisites:- None

Problem :- Add 1 to a very large number represented as a string and printing the result. Since the number is too large to fit in a standard integer data type, manipulate the digits of the string to perform the addition operation…

Explanation :-
The addition is carried out digit by digit, handling large numbers represented as strings without causing overflow errors:-
Start from the rightmost digit of the given number (string representation).
Initialize a carry variable as 1, indicating that we’re adding 1 to the number.
Traverse the digits of the number from right to left:
Convert the current digit from character to integer.
Add the carry to the current digit.
Update the digit to the sum modulo 10 (to get the single digit result).
Update the carry by dividing the sum by 10 (to get the carry for the next iteration).
After processing all digits, if there’s still a non-zero carry, add it as the most significant digit.
Reverse the digits to get the final result.
Print the result.

Solution :-
C++ Solution : -

#include <iostream>
using namespace std;

int main() {
    int t;
    string n;
    cin >> t;
    while (t--) {
        cin >> n;
        
        // Assume we need to add 1 to the last digit initially
        bool carry = true; 
        for (int i = n.length() - 1; i >= 0 && carry; i--) {
            if (n[i] == '9') {
                // If the digit is '9', it becomes '0' and carry remains true
                n[i] = '0';
            } else {
                // Increment the digit and set carry to false as we are done
                n[i] = n[i] + 1; 
                carry = false;
            }
        }
        if (carry) {
            // If carry is still true after the loop, all digits were '9', so we prepend '1' to handle the carry
            n = "1" + n;
        }
        cout << n << endl;
    }
}