📜  十进制数的9的补码

📅  最后修改于: 2021-05-07 06:03:26             🧑  作者: Mango

十进制数的9的补码是从9减去它的每个数字。与1的补码一样,9的补码用于通过加法减去一个数字。
例如,让我们使用9的补码和加法计算值“ 718 – 123”。我们首先找到718的9的补数,即281。现在我们将281加到123。得到404。9的补数为595,等于“ 718 – 123”。因此我们可以使用加法和9的补码找到减法。
如果最终获得了一个进位,也称为末尾进位,则应将其添加到答案中,并删除进位本身。例如,(83-25),25的9的补码是74和(83 + 74 = 157)。获得进位,现在将其加到数字57(57 + 1 = 58)就是答案。
给定十进制数字n,找到该数字的9的补码。

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

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

让数字存储为字符串。我们遍历数字的位数,并从9中减去每一位数。

C++
// C++ program to find 9's complement of a
// number.
#include
using namespace std;
 
void complement(string number)
{
    for (int i=0 ; i < number.length() ; i++ )
        if (number[i] != '.')
            number[i] = '9' - number[i] + '0';
 
    cout << "9's complement is : " << number;
}
 
// Driver code
int main()
{
    string number = "345.45";
    complement(number);
    return 0;
}


Java
// Java program to find 9's complement of a
// number.
 
class GFG{
static void complement(String number1)
{
    char[] number=number1.toCharArray();
    for (int i=0 ; i < number.length ; i++ )
        if (number[i] != '.')
            number[i] = (char)((int)('9') - (int)(number[i]) + (int)('0'));
    System.out.println( "9's complement is : "+String.valueOf(number));
}
 
// Driver code
public static void main(String[] args)
{
    String number = "345.45";
    complement(number);
}
}
//This code is contributed by mits


Python3
# Python3 program to find 9's
# complement of a number.
 
def complement(number):
 
    for i in range(0, len(number)):
        if(number[i] != '.'):
            a = 9 - int(number[i])
            number = (number[:i] +
                     str(a) + number[i + 1:])
 
    print("9's complement is : ", number)
 
 
# Driver code
if __name__=='__main__':
    number = "345.45"
    complement(number)
 
# This code is contributed by
# Sanjit_Prasad


C#
// C# program to find 9's complement of a
// number.
using System;
 
class GFG{
static void complement(string number1)
{
    char[] number=number1.ToCharArray();
    for (int i=0 ; i < number.Length ; i++ )
        if (number[i] != '.')
            number[i] = (char)((int)('9') -
                    (int)(number[i]) + (int)('0'));
    System.Console.WriteLine( "9's complement is : "
                                +new string(number));
}
 
// Driver code
public static void Main()
{
    String number = "345.45";
    complement(number);
}
}
//This code is contributed by mits


PHP


Javascript


输出:

9's complement is : 654.54