Last Updated: 19 May, 2021

Encrypt The Digits

Easy
Asked in company
Microsoft

Problem statement

Given a numeric string ‘STR’ which is a string containing numeric characters from ‘0’ to ‘9’, you have to encrypt the string by changing each numeric character as shown below:

‘0’ -> ‘9’

‘1’ -> ‘8’

‘2’ -> ‘7’ and so on till ‘9’ -> ‘0’

For Example :
If ‘STR’ = “8034”, then the encrypted string will be “1965”.
Input Format :
The first line contains a single integer T representing the number of test cases.

The first line of each test case contains an integer ‘N’ denoting the length of the string ‘STR’.

The second line of each test case contains the string ‘STR’.
Output Format :
For each test case, return a string denoting the encrypted numeric string.
Note:
You don’t need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
1 <= N <= 10^4
‘0’ <= STR[i] <= ‘9’

Time Limit: 1 sec

Approaches

01 Approach

The idea is to simply encrypt each character using switch case statement or if-else ladder, where output character for each input character is taken care of.
 

Here is the algorithm:

 

  1. Run a loop from 0 to ‘N-1’ (say iterator = i):
    • Initialize a character ‘ch’ = ‘STR[i]’.
    • Use an if-else ladder to initialize the value of ‘STR[i]’ according to ‘ch’. For eg - if ‘ch’ equals ‘0’ , ‘STR[i]’ = ‘9’, if ‘ch’ equals ‘1’ , ‘STR[i]’ = ‘8’ and so on.
  2. Finally, return ‘STR’.

02 Approach

Notice carefully that the sum of the numerical value of the original character and the resulting character is always equal to 9. For example, 3 is converted to 6 and the sum of 3 and 6 is 9. 

We will use the above idea and do an arithmetic operation on each character to encrypt it into the required character using ASCII values.

 

Here is the algorithm:

 

  1. Run a loop from 0 to ‘N-1’ (say iterator = i):
    • ‘STR[i]’ = ‘0’ + (‘9’ - ‘STR[i]’). (Here, note that each character is first automatically to its corresponding ASCII value when some arithmetic operation is performed on them, for example, ‘A’ + ‘B’ is equivalent to 65 + 66).
  2. Finally, return ‘STR’.