Modify characters of a string by adding integer values of same-indexed characters from another given string
Given two strings S and N of the same length, consisting of alphabetical and numeric characters respectively, the task is to generate a new string obtained by adding the integer value of each character of string N with the ASCII value of the same indexed character of string S. Finally, print the resultant string.
Note: If the sum exceeds 122, then subtract 26 from the sum and print the resultant character.
Input: S = “sun”, N = “966”
ASCII value of ‘s’ = 115.
Therefore, 115 + 9 = 124 – 26 = 98. Therefore, equivalent character is’b’.
ASCII value of ‘u’ = 117.
Therefore, 117 + 6 = 123 – 26 = 97. Therefore, equivalent character is ‘a’.
ASCII value of ‘n’ = 110.
Therefore, 110 + 6 = 116. Therefore, equivalent character is ‘t’.
Input: S = “apple”, N = “12580”
Approach: Follow the steps below to solve the problem:
- Traverse the string S:
- Convert the current character of string N to its equivalent integer value.
- Add the obtained integer value to the equivalent ASCII value of the current character in string S.
- If the value exceeds 122, which is the ASCII value of the last alphabet ‘z’, then subtract the value by 26.
- Update string S by replacing a current character with the character whose ASCII value is equal to the value obtained.
- Print the resultant string after completing the above steps.
Below is the implementation of the above approach:
Time Complexity: O(|S|)
Auxiliary Space: O(1)