在 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