📜  上一个数字与1的补码相同

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

给定数字,请检查其前任及其1的补码的二进制表示形式是否相同。

例子:

简单方法:在这种方法中,我们实际上是计算数字的补数。

1.使用简单的十进制到二进制表示技术,找到数字的前身的二进制表示形式及其数字的1。

2.逐位比较以检查它们是否相等。

3.如果所有位都相等,则打印“是”,否则打印“否”。

时间复杂度: O(log n),因为正在计算数字的二进制表示形式。

辅助空间: O(1),尽管辅助空间为O(1),但仍有一些内存空间
用于存储数字的二进制表示形式。

高效方法:只有2的幂的数字才能对其前任和其1的补码进行二进制表示。

1.检查数字是否为2的幂。

2.如果数字是2的幂,则打印YES,否则打印NO。

C++
// An efficient C++ program to check if binary
// representations of n's predecessor and its
// 1's complement are same.
#include 
#define ull unsigned long long int
using namespace std;
  
// Returns true if binary representations of
// n's predecessor and it's 1's complement are same.
bool bit_check(ull n)
{
    if ((n & (n - 1)) == 0)
        return true;
    return false;
}
  
int main()
{
    ull n = 14;
    cout << bit_check(n) << endl;
    return 0;
}


Java
// An efficient java program to check if binary
// representations of n's predecessor and its
// 1's complement are same.
public class GFG {
      
    // Returns true if binary representations of
    // n's predecessor and it's 1's complement
    // are same.
    static boolean bit_check(int n)
    {
        if ((n & (n - 1)) == 0)
            return true;
        return false;
    }
   
    // Driver code    
    public static void main(String args[]) {
          
         int n = 14;
         if(bit_check(n))
            System.out.println ('1');
         else
            System.out.println('0');
           
    }
}
  
// This code is contributed by Sam007


Python3
# An efficient Python 3 program to check 
# if binary representations of n's predecessor 
# and its 1's complement are same.
  
# Returns true if binary representations 
# of n's predecessor and it's 1's 
# complement are same.
def bit_check(n):
    if ((n & (n - 1)) == 0):
        return True
    return False
  
# Driver Code
if __name__ == '__main__':
    n = 14
    if(bit_check(n)):
        print('1')
    else:
        print('0')
      
# This code is contributed by
# Surendra_Gangwar


C#
// An efficient C# program to check if binary
// representations of n's predecessor and its
// 1's complement are same.
using System;
using System.Collections.Generic;
  
class GFG {
    
    // Returns true if binary representations of
    // n's predecessor and it's 1's complement
    // are same.
    static bool bit_check(int n)
    {
        if ((n & (n - 1)) == 0)
            return true;
        return false;
    }
  
    public static void Main()
    {
         int n = 14;
         if(bit_check(n))
            Console.WriteLine ('1');
         else
            Console.WriteLine ('0');
    }
}
  
// This code is contributed by Sam007


PHP


输出:
0

时间复杂度: O(1)

辅助空间: O(1)没有多余的空间被使用。