編寫高效的C++方法檢查數字是否為3的倍數
在這裡,我們需要編寫一個程式來檢查給定的數字是否為3的倍數。
一個通用的解決方案是一個簡單的解決方案,將數字的所有位數相加,如果和是3的倍數,則該數字可被3整除,否則不可被3整除。但是,此解決方案並非最有效的解決方案。
一個有效的解決方案是使用數字二進位制表示中設定位的計數。*如果奇數位設定位計數與偶數位設定位計數之間的差是3的倍數,則該數字是3的倍數。*
我們將使用迴圈並移位數字的位,並計算奇數和偶數位置的位數。最後,我們將返回檢查差值是否為三的倍數。
讓我們舉個例子來理解實現:
輸入
n = 24
輸出
even
解釋
binary representation = 11000 Evensetbits = 1 , oddsetbits = 1. Difference = 0, it is divisible.
程式展示了我們解決方案的實現:
示例
#include <bits/stdc++.h>
using namespace std;
int isDivisibleBy3(int n) {
int oddBitCount = 0;
int evenBitCount = 0;
if (n < 0)
n = -n;
if (n == 0)
return 1;
if (n == 1)
return 0;
while (n) {
if (n & 1)
oddBitCount++;
if (n & 2)
evenBitCount++;
n = n >> 2;
}
return isDivisibleBy3(oddBitCount - evenBitCount);
}
int main() {
int n = 1241;
cout<<"The number "<<n;
if (isDivisibleBy3(n))
cout<<" is a multiple of 3";
else
cout<<" is not a multiple of 3";
return 0;
}輸出
The number 1241 is not a multiple of 3
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP