VOOZH about

URL: https://www.geeksforgeeks.org/dsa/9s-complement-decimal-number/

⇱ 9's complement of a decimal number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

9's complement of a decimal number

Last Updated : 28 Feb, 2023

9's complement of a decimal number is the subtraction of it's each digits from 9. Like 1's complement, 9's complement is used to subtract a number using addition.
For example, let us compute value of "718 - 123" using 9's complement and addition. We first find 9's complement of 718 which is 281. Now we add 281 to 123. We get 404. 9's complement of this is 595 which is equal to "718 - 123". So we could find subtraction using addition and 9's complement.
In case while adding a carry is obtained in the end, also known as the end around carry, it should be added to the answer, removing the carry itself. For example, (83-25) , 9's complement of 25 is 74 and (83+74 = 157). A carry is obtained, now add it to the number 57, (57+1 = 58) which is the answer.

Given a decimal number n, find 9's complement of the number. 

Input : 25
Output : 9's complement is : 74

Input : 345.45
Output : 9's complement is : 654.54

Let the number be stored as string. We traverse digits of number and subtract every digit from 9.

Output:  

9's complement is : 654.54

Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), as the input string is being modified in place and no additional data structure is being used.


Comment
Article Tags: