Find the next number by adding natural numbers in order on alternating indices from last


A numerical string is used to store a value of a number if we want to store a huge valued integer. As we know, we can not store a number greater than 32 bits in the computer with its datatype as int. So to avoid the overflowing condition, in this problem, we will take a numerical string as our input rather than an int variable so that we can work this problem on a larger scale of numbers.

Problem Statement

Now, in this problem, we need to find the following number by adding natural numbers in order on alternating indices from the last. We would be given a numerical string and have to return the final output as the string itself. Let us see how we should proceed to solve this problem.

Let’s try to understand this problem with the help of some examples.

Input

s = “12345678”

Output

16375879

Explanation

  • Firstly, we will take the last digit ‘8’ and add the first natural number ‘1’ to it. We will get (8 + 1) = 9 as the last digit of the new numeric string.

  • Then we will keep ‘7’ as it is as we have to perform the operations alternatively.

  • Next, we will take ‘6’ and add the second natural number ‘2’ to it. We will get (6 + 2) = 8 as our third digit of the new numeric string.

  • Then we will keep ‘5’ as it is as we have to perform the operations alternatively.

  • Next, we will take ‘4’ and add the third natural number ‘3’ to it. We will get (4 + 3) = 7 as our fifth digit of the new numeric string.

  • Then we will keep ‘3’ as it is as we have to perform the operations alternatively.

  • Next, we will take ‘2’ and add forth the natural number ‘4’ to it. We will get (2 + 4) = 6 as our seventh digit of the new numeric string.

  • Then we will keep ‘1’ as it is as we have to perform the operations alternatively.

  • Hence, we will get our final numeric string as “16375879”

Input

s = “78930”

Output

18231

Explanation

  • Firstly, we will take the last digit ‘0’ and add the first natural number ‘1’ to it. We will get (0 + 1) = 1 as the last digit of the new numeric string.

  • Then we will keep ‘3’ as it is as we have to perform the operations alternatively.

  • Next, we will take ‘9’ and add the second natural number ‘2’ to it. We will get (9 + 2) = 11

  • Now, we need to convert this digit into a single digit and we can easily do that by taking its modulo with 9 which would give us ‘2’ as our third digit of the new numeric string.

  • Then we will keep ‘8’ as it is as we have to perform the operations alternatively.

  • Next, we will take ‘7’ and add the third natural number ‘3’ to it. We will get (7 + 3) = 10

  • Now, we need to convert this digit into a single digit and we can easily do that by taking its modulo with 9 which would give us ‘1’ as our fifth digit of the new numeric string.

  • Hence, we will get our final numeric string as “18231”

Problem Explanation

Let’s try to understand the problem and find its solution. In this problem, we are given a numeric string and we have to alter our string by keeping the following conditions in our mind −

  • Add the natural number starting from 1, 2, 3, and so on up to infinity in the alternative digit starting from the last.

  • It means we will alter the digits located at odd positions if we start the last digit as one place digit indexing 1 and keep the rest of the digits as such.

  • If we do not get a single digit after addition, we are supposed to make it single by continuously adding the number until it is changed to a single-digit number, or else we can use another logic by taking the modulo of the altered digit to 9 which will give us the same value and will provide us a single digit as well in less time.

In the following article, we will understand this simple approach with the help of the comments given in the easy code −

Algorithm

  • Define a temporary number and initialize addNum with ‘0’.

  • Define an empty string that would contain the final output.

  • Run a loop from the back of the string and convert characters into integers.

  • If the digit is at an even position add natural numbers starting from 1 to infinity for different digits.

  • Convert the number we would get after addition into a single-digit number.

  • Convert the number into the character.

  • Append the character into the final output string.

Example

The following are implementations of the above approach in various programming languages −

#include <bits/stdc++.h>
using namespace std;
// Function to find the next number by adding natural numbers in order on alternating indices from last
string Helper(string s){
   // Define a temporary integer
   // Initialize the number we will add in the numeric string integers by 0
   int temp = 0, addNum = 0;
   // Define the empty string ans
   string ans = "";
   // Store the length of the numerical string
   int n = s.size();
   // Start the loop to get the new string
   for (int i = n - 1; i >= 0; i--) {
      // Store the digit at ith position in the integer form rather character form
      int num = s[i] - '0';
      // Check if the position is even or not, if even alter the digit
      if (temp % 2 == 0) {
         addNum += 1;
         num += addNum;
         // Check if the digit becomes greater than or equal to 10
         if (num >= 10) {
            // If yes, we need to take a modulus of 9 to make it single digit
            num %= 9;
            // Check if the single digit is 0, and change the digit back to 9
            if (num == 0)
               num = 9;
         }
      }
      // Store the result
      ans = to_string(num) + ans;
      temp += 1;
   }
   // Return the result
   return ans;
}
int main(){
   // Give the input string of numerical
   string s = "12345678";
   // Call the Helper function
   cout << "The following number by adding natural numbers in order on alternating indices on the string " << s << " from the last is: "<< Helper(s);
   return 0;
}

Output

The following number by adding natural numbers in order on alternating indices on the string 12345678 from the last is: 16375879
public class Main {
   public static String Helper(String s) {
      // Define a temporary integer
      // Initialize the number we will add in the numeric string integers by 0
      int temp = 0, addNum = 0;
      // Define the empty string ans
      StringBuilder ans = new StringBuilder();
      int n = s.length();
      for (int i = n - 1; i >= 0; i--) {
         int num = Character.getNumericValue(s.charAt(i));
         // Check if the position is even or not, if even alter the digit
         if (temp % 2 == 0) {
            addNum += 1;
            num += addNum;
            // Check if the digit becomes greater than or equal to 10
            if (num >= 10) {
               // If yes, we need to take a modulus of 9 to make it single digit
               num %= 9;
               // Check if the single digit is 0, and change the digit back to 9
               if (num == 0) {
                  num = 9;
               }
            }
         }
         ans.insert(0, num);
         temp += 1;
      }
      // Return the result
      return ans.toString();
   }
   public static void main(String[] args) {
      // Give the input string of numerical
      String s = "12345678";
      // Call the Helper function
      String result = Helper(s);
      System.out.println("The following number by adding natural numbers in order on alternating indices on the string " + s + " from the last is: " + result);
   }
}

Output

The following number by adding natural numbers in order on alternating indices on the string 12345678 from the last is: 16375879
def Helper(s):
   # Define a temporary varaible
   # Initialize the number we will add in the numeric by 0
   temp = 0
   addNum = 0
   # Define the empty ans
   ans = ""
   n = len(s)
   # Start the loop to get the new string
   for i in range(n - 1, -1, -1):
      num = int(s[i])
      # Check if the position is even or not, if even alter the digit
      if temp % 2 == 0:
         addNum += 1
         num += addNum
         # Check if the digit becomes greater than or equal to 10
         if num >= 10:
            # If yes, we need to take a modulus of 9 to make it single digit
            num %= 9
            # Check if the single digit is 0, and change the digit back to 9
            if num == 0:
               num = 9
      ans = str(num) + ans
      temp += 1
   # Return the result
   return ans
    
# Give the input string of numerical
s = "12345678"
# Call the Helper function
result = Helper(s)
print("The following number by adding natural numbers in order on alternating indices on the string", s, "from the last is:", result)

Output

The following number by adding natural numbers in order on alternating indices on the string 12345678 from the last is: 16375879

Complexities for the Above Code

  • Time complexity − O(n); where n is the length of the string

  • Space complexity − O(1); We have not stored any variable in some data structure in the above code.

Conclusion

In this article, find the following number by adding the natural numbers in order on alternating indices from the last. We got to the solution by applying operations on the alternative digits from the last and keeping the remaining digits as such. We will use a string of digits instead of using the actual digits so that we can work on a number having a large value with more and more digits included in it.

Updated on: 05-Feb-2024

59 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements