10’s Complement of a decimal number
Last Updated :
01 Sep, 2022
Given a decimal number N. The task is to find 10’s complement of the number N.
Example:
Input : 25
Output : 10's complement is : 75
Input : 456
Output : 10's complement is : 544
10’s complement of a decimal number can be found by adding 1 to the 9’s complement of that decimal number. It is just like 2s complement in binary number representation.
Mathematically,
10’s complement = 9’s complement + 1
For example, let us take a decimal number 456, 9’s complement of this number will be 999-456 which will be 543. Now 10s complement will be 543+1=544.
Therefore,
10’s complement = 10len – num
Where, len = total number of digits in num.
Below is the program to find 10’s complement of a given number:
C++
#include<iostream>
#include<cmath>
using namespace std;
int complement( int num)
{
int i,len=0,temp,comp;
temp = num;
while (1)
{
len++;
num=num/10;
if ( abs (num)==0)
break ;
}
num = temp;
comp = pow (10,len) - num;
return comp;
}
int main()
{
cout<<complement(25)<<endl;
cout<<complement(456);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int complement( int num)
{
int i, len = 0 , temp, comp;
temp = num;
while ( true )
{
len++;
num = num / 10 ;
if (Math.abs(num) == 0 )
break ;
}
num = temp;
comp = ( int )Math.pow( 10 ,len) - num;
return comp;
}
public static void main (String[] args)
{
System.out.println(complement( 25 ));
System.out.println(complement( 456 ));
}
}
|
Python3
import math
def complement(num):
i = 0 ;
len = 0 ;
comp = 0 ;
temp = num;
while ( 1 ):
len + = 1 ;
num = int (num / 10 );
if ( abs (num) = = 0 ):
break ;
num = temp;
comp = math. pow ( 10 , len ) - num;
return int (comp);
print (complement( 25 ));
print (complement( 456 ));
|
C#
using System;
class GFG
{
static int complement( int num)
{
int len = 0, temp, comp;
temp = num;
while ( true )
{
len++;
num = num / 10;
if (Math.Abs(num) == 0)
break ;
}
num = temp;
comp = ( int )Math.Pow(10, len) - num;
return comp;
}
public static void Main ()
{
Console.WriteLine(complement(25));
Console.WriteLine(complement(456));
}
}
|
PHP
<?php
function complement( $num )
{
$i ;
$len = 0;
$comp ;
$temp = $num ;
while (1)
{
$len ++;
$num = (int)( $num / 10);
if ( abs ( $num ) == 0)
break ;
}
$num = $temp ;
$comp = pow(10, $len ) - $num ;
return $comp ;
}
echo complement(25) . "\n" ;
echo complement(456);
?>
|
Javascript
<script>
function complement(num) {
var i, len = 0, temp, comp;
temp = num;
while ( true ) {
len++;
num = parseInt(num / 10);
if (Math.abs(num) == 0)
break ;
}
num = temp;
comp = parseInt( Math.pow(10, len) - num);
return comp;
}
document.write(complement(25)+ "<br/>" );
document.write(complement(456));
</script>
|
Time Complexity: O(logn) where n is the given number
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...