📜  二进制字符串的2的补码的有效方法

📅  最后修改于: 2021-04-27 23:35:49             🧑  作者: Mango

给定一个二进制数作为字符串,打印其2的补码。

二进制数的2的补码为1,再加上二进制数的1的补码。请注意,1的补码只是给定二进制数的翻转。
例子:

2's complement of "0111" is  "1001"
2's complement of "1100" is  "0100" 

我们强烈建议您单击此处并进行实践,然后再继续解决方案。

我们在下面的文章中讨论了1和2的补码。

二进制数的1和2的补码。

上面讨论的方法遍历二进制字符串两次以找到2的补码,首先找到1的补码,然后使用1的补码找到2的补码

在这篇文章中,讨论了有效的2补码方法,该方法仅遍历字符串一次。我们从最后开始遍历字符串,直到没有遍历单个1,然后翻转所有字符串值,即0到1和1到0。

注:这里如果1没有在字符串中只追加1字符串的开始存在,那么处理极端情况即。

插图 :

Input:  str = "1000100"
Output:        0111100
Explanation: Starts traversing the string from last,
we got first '1' at index 4 then just flip the bits 
of 0 to 3 indexes to make the 2's complement. 

Input:  str =  "0000"
Output:        10000
Explanation: As there is no 1 in the string so just 
append '1' at starting.
C++
// An efficient C++ program to find 2's complement
#include
using namespace std;
  
// Function to find two's complement
string findTwoscomplement(string str)
{
    int n = str.length();
  
    // Traverse the string to get first '1' from
    // the last of string
    int i;
    for (i = n-1 ; i >= 0 ; i--)
        if (str[i] == '1')
            break;
  
    // If there exists no '1' concatenate 1 at the
    // starting of string
    if (i == -1)
        return '1' + str;
  
    // Continue traversal after the position of
    // first '1'
    for (int k = i-1 ; k >= 0; k--)
    {
        //Just flip the values
        if (str[k] == '1')
            str[k] = '0';
        else
            str[k] = '1';
    }
  
    // return the modified string
    return str;;
}
  
// Driver code
int main()
{
    string str = "00000101";
    cout << findTwoscomplement(str);
    return 0;
}


Java
// An efficient Java program to find 2's complement
  
class Test
{
    // Method to find two's complement
    static String findTwoscomplement(StringBuffer str)
    {
        int n = str.length();
       
        // Traverse the string to get first '1' from
        // the last of string
        int i;
        for (i = n-1 ; i >= 0 ; i--)
            if (str.charAt(i) == '1')
                break;
       
        // If there exists no '1' concat 1 at the
        // starting of string
        if (i == -1)
            return "1" + str;
       
        // Continue traversal after the position of
        // first '1'
        for (int k = i-1 ; k >= 0; k--)
        {
            //Just flip the values
            if (str.charAt(k) == '1')
                str.replace(k, k+1, "0");
            else
                str.replace(k, k+1, "1");
        }
       
        // return the modified string
        return str.toString();
    }
      
    // Driver method
    public static void main(String[] args) 
    {
        StringBuffer str = new StringBuffer("00000101");
        System.out.println(findTwoscomplement(str));
    }
}


Python3
# An efficient Python 3 program to 
# find 2's complement
  
# Function to find two's complement
def findTwoscomplement(str):
    n = len(str)
  
    # Traverse the string to get first 
    # '1' from the last of string
    i = n - 1
    while(i >= 0):
        if (str[i] == '1'):
            break
  
        i -= 1
  
    # If there exists no '1' concatenate 1 
    # at the starting of string
    if (i == -1):
        return '1'+str
  
    # Continue traversal after the 
    # position of first '1'
    k = i - 1
    while(k >= 0):
          
        # Just flip the values
        if (str[k] == '1'):
            str = list(str)
            str[k] = '0'
            str = ''.join(str)
        else:
            str = list(str)
            str[k] = '1'
            str = ''.join(str)
  
        k -= 1
  
    # return the modified string
    return str
  
# Driver code
if __name__ == '__main__':
    str = "00000101"
    print(findTwoscomplement(str))
  
# This code is contributed by
# Sanjit_Prasad


C#
// An efficient c# program to find 2's complement 
using System;
using System.Text;
  
class GFG
{
// Method to find two's complement 
public static string findTwoscomplement(StringBuilder str)
{
    int n = str.Length;
  
    // Traverse the string to get 
    // first '1' from the last of string 
    int i;
    for (i = n - 1 ; i >= 0 ; i--)
    {
        if (str[i] == '1')
        {
            break;
        }
    }
  
    // If there exists no '1' concat 1 
    // at the starting of string 
    if (i == -1)
    {
        return "1" + str;
    }
  
    // Continue traversal after the
    // position of first '1' 
    for (int k = i - 1 ; k >= 0; k--)
    {
        // Just flip the values 
        if (str[k] == '1')
        {
            str.Remove(k, k + 1 - k).Insert(k, "0");
        }
        else
        {
            str.Remove(k, k + 1 - k).Insert(k, "1");
        }
    }
  
    // return the modified string 
    return str.ToString();
}
  
// Driver Code 
public static void Main(string[] args)
{
    StringBuilder str = new StringBuilder("00000101");
    Console.WriteLine(findTwoscomplement(str));
}
}
  
// This code is contributed by Shrikant13


PHP
= 0 ; $i--)
        if ($str[$i] == '1')
            break;
  
    // If there exists no '1' concatenate
    // 1 at the starting of string
    if ($i == -1)
        return '1' + $str;
  
    // Continue traversal after the 
    // position of first '1'
    for ($k = $i-1 ; $k >= 0; $k--)
    {
        // Just flip the values
        if ($str[$k] == '1')
            $str[$k] = '0';
        else
            $str[$k] = '1';
    }
  
    // return the modified string
    return $str;;
}
  
// Driver code
$str = "00000101";
echo findTwoscomplement($str);
  
// This code is contributed by jit.
?>


输出:

11111011