在 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

更新於: 03-Feb-2020

289 次瀏覽

職業快速入門

完成課程獲得認證

開始
廣告
© . All rights reserved.