码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Power of Two

时间:2015-12-20 07:03:54      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

Given an integer, write a function to determine if it is a power of two.

还是有一个地方不小心:Integer.MIN_VALUE, 应该是false,但是因为只有一个1,我曾经判断为true。事实上,所有negative value都应该是false

 1 public class Solution {
 2     public boolean isPowerOfTwo(int n) {
 3         boolean one = false;
 4         for (int i=0; i<32; i++) {
 5             if (((n>>i) & 1) == 1) {
 6                 if (i == 31) return false;
 7                 if (!one) one = true;
 8                 else return false;
 9             }
10         }
11         return one;
12     }
13 }

 

Leetcode: Power of Two

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/5060206.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!