Generate string by incrementing character of given string by number present at corresponding index of second string
Given two strings S[] and N[] of the same size, the task is to update string S[] by adding the digit of string N[] of respective indices.
Examples:
Input: S = “sun”, N = “966”
Output: bat
Input: S = “apple”, N = “12580”
Output: brute
Approach: The idea is to traverse the string S[] from left to right. Get the ASCII value of string N[] and add it to the ASCII value of string S[]. If the value exceeds 122, which is the ASCII value of the last alphabet ‘z’. Then subtract the value by 26, which is the total count of English alphabets. Update string S with the character of ASCII value obtained. Follow the steps below to solve the problem:
- Iterate over the range [0, S.size()) using the variable i and perform the following tasks:
- Initialize the variables a and b as the integer and ascii value of N[i] and S[i].
- If b is greater than 122 then subtract 26 from b.
- Set S[i] as char(b).
- After performing the above steps, print the value of S[] as the answer.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
string updateStr(string S, string N)
{
for ( int i = 0; i < S.size(); i++) {
int a = int (N[i]) - '0' ;
int b = int (S[i]) + a;
if (b > 122)
b -= 26;
S[i] = char (b);
}
return S;
}
int main()
{
string S = "sun" ;
string N = "966" ;
cout << updateStr(S, N);
return 0;
}
|
Java
import java.util.*;
public class GFG {
static String updateStr(String S, String N)
{
String t = "" ;
for ( int i = 0 ; i < S.length(); i++) {
int a = ( int )(N.charAt(i) - '0' );
int b = ( int )(S.charAt(i) + a);
if (b > 122 )
b -= 26 ;
char x = ( char )b;
t +=x;
}
return t;
}
public static void main(String args[])
{
String S = "sun" ;
String N = "966" ;
System.out.println(updateStr(S, N));
}
}
|
Python3
def updateStr(S, N):
S = list (S)
for i in range ( len (S)):
a = ord (N[i]) - ord ( '0' )
b = ord (S[i]) + a
if (b > 122 ):
b - = 26
S[i] = chr (b)
return "".join(S)
S = "sun"
N = "966"
print (updateStr(S, N))
|
C#
using System;
public class GFG {
static String updateStr(String S, String N)
{
String t = "" ;
for ( int i = 0; i < S.Length; i++) {
int a = ( int )(N[i] - '0' );
int b = ( int )(S[i] + a);
if (b > 122)
b -= 26;
char x = ( char )b;
t +=x;
}
return t;
}
public static void Main(String []args)
{
String S = "sun" ;
String N = "966" ;
Console.WriteLine(updateStr(S, N));
}
}
|
Javascript
<script>
function updateStr(S, N) {
S = S.split( '' )
for (let i = 0; i < S.length; i++) {
let a = (N[i].charCodeAt(0) - '0' .charCodeAt(0));
let b = (S[i].charCodeAt(0)) + a;
if (b > 122)
b -= 26;
S[i] = String.fromCharCode(b);
}
return S.join( '' );
}
let S = "sun" ;
let N = "966" ;
document.write(updateStr(S, N));
</script>
|
Time Complexity: O(|S|)
Auxiliary Space: O(1)
Last Updated :
07 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...