在 C++ 中判断给定数字是否为 4 的幂
在这个问题中,我们得到了一个整数 N。我们的任务是判断给定的整数是否是 4 的幂。
我们举例来理解这个问题,
Input : N = 64 Output : Yes
说明 −
43 = 64
解决方案方法
解决这个问题的一个简单方法是递归地将数字除以 4,并检查所得数字是否可以除以 4。如果递归除法后的值变为 1,则返回 true。
示例
演示我们解决方案工作原理的程序
#include <iostream>
using namespace std;
bool isPowerOf4(int n){
if(n == 0)
return 0;
while(n != 1)
{
if(n % 4 != 0)
return 0;
n = n / 4;
}
return 1;
}
int main(){
int n = 123454;
if (isPowerOf4(n))
cout<<"The number is a power of 4";
else
cout<<"The number is not a power of 4";
return 0;
}输出
The number is not a power of 4
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP