在 C++ 中,前一个数字与 1 的补码相同
在这个问题中,我们给出了一个整数 n。我们的任务是检查前面的数字是否等于该数字的 1 的补码。
让我们举几个例子来理解我们的问题
Input: 12 Output: No Explanation: (12)10 = (1100)2 Preceding number 11 = (1011)2 1’s complement of 12 = (0011)2 Input: 4 Output: Yes Explanation: 4 = (100)2 Preceding number 3 = (011)2 1’s complement of 12 = (011)2
为了解决这个问题,我们可以使用一种简单的方法,即比较前面的数字和该数字的 1 的补码。
这种方法很简单,但会消耗空间和时间。时间复杂度:O(n)
一种有效的方法可以是使用我们寻求解决问题的一般方法。在这里,只有 2 的幂才能满足该条件,即前面的数字等于 1 的补码。
程序展示我们解决方案的实现
示例
#include <iostream>
using namespace std;
bool sameBits(unsigned long int n){
if ((n & (n - 1)) == 0)
return true;
return false;
}
int main(){
unsigned long int n = 64;
if(sameBits(n))
cout<<"Both are the same";
else
cout<<"Both aren't the same";
return 0;
}输出
Both are the same
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP