Home > Database > Mysql Tutorial > 判断一个整数是不是2的整数次幂

判断一个整数是不是2的整数次幂

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-07 15:36:46
Original
1814 people have browsed it

#includeiostream using namespace std; //第一种方法利用循环 bool MakeDecision(const int M,int pow) //pow表示M是2的多少次幂 { int i=2; int s=1; pow=0; if(M0) return false; if(M==0) return true; do { s*=i; pow; }while(sM); if(s==M) return tru

#include

using namespace std;

//第一种方法利用循环
bool MakeDecision(const int& M,int &pow) //pow表示M是2的多少次幂
{
 int i=2;
 int s=1;
 pow=0;
 if(M  if(M==0) return true;
 do
 {
  s*=i;
  pow++;
 }while(s  if(s==M) return true;
 else
 {
  pow=0;
  return false;
 }
}

//第二种方法,如果M/2是2的整数次幂,那么M就是2的整数次幂,递归实现
bool MakeDecision(int M,int *pow)
{
 if(M  if(M%2!=0) return false;
 if(M==0) return true;
 else if(M==2)
 {
  *pow=*pow+1;
  return true;
 }
 else
 {
  *pow=*pow+1;
  MakeDecision(M/2,pow);
 }
}

//一个是2的整数次幂的整数,它的第0,1,2...都是1,而其余位都是0,这样-M的补码有1位1的位置和M的补码1的位置是相同的
//因此M & -M 就是M
bool MakeDecision(int& M)
{
 return M == (M & (-M));
}

void main()
{
 cout  int M;
 cin>>M;
 int pow=0;
 //if(MakeDecision(M,&pow)) cout  if(MakeDecision(M)) cout  else cout }

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template