LintCode: O(1) Check Power of 2

简介:

C++

去掉二进制最右边的1

复制代码
 1 class Solution {
 2 public:
 3     /*
 4      * @param n: An integer
 5      * @return: True or false
 6      */
 7     bool checkPowerOf2(int n) {
 8         // write your code 
 9         if ( n <= 0 ){
10             return false;
11         }
12         int m = n&(n-1);
13         return m==0?true:false;
14     }
15 };
复制代码

C++

统计二进制中的1的个数

复制代码
 1 class Solution {
 2 public:
 3     /*
 4      * @param n: An integer
 5      * @return: True or false
 6      */
 7     bool checkPowerOf2(int n) {
 8         // write your code here
 9         int cnt=0;
10         if(n <= 0){
11             return false;
12         }
13         while(n!=0){
14             cnt += n&1;
15             n = n>>1;
16             if(cnt == 2){
17                 return false;
18             }
19         }
20         return true;
21     }
22 };
复制代码

 


本文转自ZH奶酪博客园博客,原文链接:http://www.cnblogs.com/CheeseZH/p/5009697.html,如需转载请自行联系原作者

相关文章
|
C语言
根本解决C程序 ignoring return value of ‘***’
去源码找到出问题的地方,处理一下返回值
363 0
|
6月前
解决Vscode使用LeetCode报错Failed to test the solution. Please open the output channel for details.
本文提供了解决在VScode中使用LeetCode插件时遇到“Failed to test the solution. Please open the output channel for details.”错误的方法,主要是通过修改setting.json文件中的输出文件夹配置来解决。
537 1
|
Ubuntu Unix Linux
成功解决ERROR: Unable to find the development tool `cc` in your path; please make sure that you have the
成功解决ERROR: Unable to find the development tool `cc` in your path; please make sure that you have the
成功解决ERROR: Unable to find the development tool `cc` in your path; please make sure that you have the
|
6月前
|
编译器 API C++
【Matlab】解决使用Mex 报错There was a problem creating the mex file for Real Time Execution ,Please ensure y
解决Matlab使用Mex时出现的"Real Time Execution"错误的步骤,即通过安装"MATLAB 支持 MinGW-w64 C/C++ 编译器"这个包来确保编译器设置正确。
96 0