编写一种有效的方法来检查C ++中数字是否为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
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短