Find the next number by adding natural numbers in order on alternating indices from last
Given a numeric string S of size N, the task is to find the number formed by adding numbers 1, 2, 3, … up to infinity to every alternative digit of the given numeric string S(starting from the last position). At any point, if the addition result is not a single digit, perform the repeated addition of digits until the result is a single digit.
Input: S = “1345”
Adding 1 to the last digit i.e., 5 will become 6 which modifies the string to “1346”.
Adding 2 to the second last digit i.e., 3 will become 5 which modifies the string to “1546”.
After the above steps, the resultant string formed is “1546”.
Input: S = “789”
Approach: The idea to solve this problem lies over the part of repeated addition. There is actually no need to perform addition repeatedly until there is one digit. Instead, perform number % 9. If the number % 9 is equal to 9, then the sum of the digits will be equal to 9, else the sum of the digits will be equal to the number % 9. Follow the steps below to solve the problem:
- Initialize the variables temp and adding_number as 0 to store the position to be altered and the number to be added.
- Initialize the string variable result as an empty string to store the result.
- Iterate over the range [len-1, 0] where len is the length of the string, using the variable i and perform the following steps:
- Initialize the variable digit as the digit at the current position in the string.
- If temp%2 equals 0 then increase the value of adding_number by 1 and add it to the variable digit.
- If digit greater than equals to 10 then set the value of digit as digit%9 and if still, digit equals 0 then set its value as 9.
- Add the variable digit to the variable result in the beginning.
- After performing the above steps, print the value of result as the answer.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)