n是2的几次方?

来源:互联网 发布:博扬博格达诺维奇数据 编辑:程序博客网 时间:2024/04/30 05:49
#include <iostream>using namespace std;void method_bxy(int n){int count = 0;while(1){if(1 == n){cout << "n为2的" << count <<"次方"<<endl;break;}if(0 == n%2){++count;n /= 2;if(n == 0){cout << "n为2的" << count <<"次方"<<endl;break;}}else{cout << "n不是2的整数次幂"<<endl;break;}}}//方法abool method_a(int n){int i=1;while(true){if(i > n){return false;}if(i == n){return true;}i = i * 2;}}//方法b:比方法a高效一些,如果不是2的整数次幂,会少循环一些~~bool method_b(int n){if(n == 1){return true;}else{do{if( n % 2 == 0){n = n / 2;}else{return false;}}while(n != 1);return true;}}//方法3:1000 & 0111 == 0bool method_c(int n){if(n < 1){return false;}else{return ((n & (n - 1)) == 0) ? true : false;}}//方法4:bool method_d(int n){if(n < 1){return false;}else{return (n & (n - 1)) == 0;}}//方法5:浮点误差毕竟不是容易避开的问题,当数很大的时候,比如//0x10000001,结果是true因为结果的小数部分是在太小了#include <math.h>bool method_e(int n){float ret = log((double)n)/log((double)2);return abs((int)ret - ret) <= 0.00001;}//方法6:void main(){int n=8;method_bxy(n);if(method_c(n))cout << "Yes"<<endl;elsecout <<"No" <<endl;}