Add index to characters and reverse the string
Last Updated :
07 Aug, 2022
Given a string str, the task is to encrypt and reverse the string. The string is encrypted by adding every character of the string with it’s index in the string i.e. if character‘a’ is at index 2 then the character in the updated string will be ‘a’ + 2 = ‘c’. Since value of string may go beyond 256, do the addition under modulo 256.
Examples:
Input: str = “geeks”
Output: wngfg
‘g’ + 0 = ‘g’
‘e’ + 1 = ‘f’
‘e’ + 2 = ‘g’
‘k’ + 3 = ‘n’
‘s’ + 4 = ‘w’
Input: str = “java”
Output: dxbj
Approach:
- Add every character of the string with its index within the same string.
- Reverse the string.
- Print the reversed string.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string getEncryptedString(string str)
{
string sb = "" ;
for ( int i = str.length() - 1; i >= 0; i--)
{
sb+=( char )(( int )str[i] + i) % 256;
}
return sb;
}
int main()
{
string str = "geeks" ;
cout<<getEncryptedString(str)<<endl;
return 0;
}
|
Java
public class HelloWorld {
static String getEncryptedString(String str)
{
StringBuilder sb = new StringBuilder( "" );
for ( int i = str.length() - 1 ; i >= 0 ; i--) {
sb.append( "" + ( char )((str.charAt(i) + i) % 256 ));
}
return sb.toString();
}
public static void main(String[] args)
{
String str = "geeks" ;
System.out.println(getEncryptedString(str));
}
}
|
Python3
def getEncryptedString( str ):
sb = "";
for i in range ( len ( str ) - 1 , - 1 , - 1 ):
sb + = chr (( ord ( str [i]) + i) % 256 );
return sb;
str = "geeks" ;
print (getEncryptedString( str ));
|
C#
using System;
using System.Text;
public class HelloWorld
{
static String getEncryptedString(String str)
{
StringBuilder sb = new StringBuilder( "" );
for ( int i = str.Length - 1; i >= 0; i--)
{
sb.Append( "" + ( char )((str[i] + i) % 256));
}
return sb.ToString();
}
public static void Main(String[] args)
{
String str = "geeks" ;
Console.WriteLine(getEncryptedString(str));
}
}
|
PHP
<?php
function getEncryptedString( $str )
{
$sb = "" ;
for ( $i = strlen ( $str ) - 1; $i >= 0; $i --)
{
$sb .= chr ((ord( $str [ $i ]) + $i ) % 256);
}
return $sb ;
}
$str = "geeks" ;
print (getEncryptedString( $str ));
?>
|
Javascript
<script>
function getEncryptedString( str)
{
sb = "" ;
for (i = str.length - 1; i >= 0; i--) {
sb+=( "" + String.fromCharCode((str.charCodeAt(i) + i) % 256));
}
return sb;
}
var str = "geeks" ;
document.write(getEncryptedString(str));
</script>
|
Time complexity: O(N) where N is length of given string
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...