Last Updated: 24 Dec, 2020

Digit Inversion

Easy
Asked in company
Ola

Problem statement

Digit Inverse of a number is a number which can be found by replacing 0 with 9, 1 with 8, 2 with 7, 3 with 6, 4 with 5 and vice versa.

Can you find the digit inverse of the given number 'N'?

Example:
Let 'N' = 1234567

Replacing 1 with 8, 2 with 7, 3 with 6, 4 with 5, 5 with 4, 6 with 3, 7 with 2. Thus the digit inverse of 'N' will be 8765432 as we replaced each digit in 'N'.
Input format:
The first line of input contains an integer ‘T’ denoting the number of test cases.

The first line of each test case contains an integer ‘N’ representing the number whose digit inverse is to be found.
Output format :
For each test case, return an integer denoting the digit inverse of the given number.
Note :
You don't need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10^5
0 <= N < 10^9

Time limit: 1 sec

Approaches

01 Approach

The approach is simple: just replace each digit with its inverse digit.

 

All we need to do is just traverse over each digit in the number and replace it with its digit inverse. We can get the last digit of a number by taking its modulo with 10 and then we will divide the number by 10 so that we can access the next digit. Simultaneously we will create a new number which is the digit inverse of the given number.

02 Approach

The second approach can be taking difference with a number having the equivalent number of 9’s as the number of digits of ‘N’.

 

If we observe that the sum of ‘N’ & digit inverse('N') = 999..9 . Here the number of 9’s is equal to the number of digits in ‘N’.

 

So, digit inverse('N') = 999..9 - ‘N’

 

  • All we need to do is just count the number of digits in ‘N’.
  • Now we will find a number ‘K’ = 10 ^ (number of digits in ‘N’) - 1.
  • Digit inverse of ‘N’ will be ‘K' - ‘N’.