Encrypt The Digits

Easy
0/40
Average time to solve is 10m
profile
Contributed by
1 upvote
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”.
Detailed explanation ( Input/output format, Notes, Images )
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
Sample Input 1:
2
5
48931
6
631840
Sample Output 1:
51068
368159
Explanation For Sample Input 1:
For the sample case 1, After encrypting the input string ‘STR’ output string looks like “51068”.

For the sample case 2, After encrypting the input string ‘STR’ output string looks like “368159”.
Sample Input 2:
2
5
39584
5
58217
Sample Output 2:
60415
41782
Explanation For Sample Input 2:
For the sample case 1, After encrypting the input string ‘STR’ output string looks like “60415”.

For the sample case 2, After encrypting the input string ‘STR’ output string looks like “41782”.
Hint

Can you encrypt each character using switch case or if else ladder?

Approaches (2)
Iterating

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’.
Time Complexity

O(N), where ‘N’ is the length of ‘STR’.

 

Total ‘N’ iterations are done in a single loop. Hence, effective time complexity is O(N).

Space Complexity

For C++

O(1)

 

Since we are not using any extra space for solving this problem, effective space complexity is O(1).

 

For Java and Python

O(N)

 

Because we are using an extra ‘TEMP’ string for storing the resultant string. Hence, effective space complexity is O(N).

Code Solution
(100% EXP penalty)
Encrypt The Digits
Full screen
Console