在这里,我们需要编写一个程序来检查给定数字是否为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