Leetcode231 Power of Two
2015-10-18 13:10
393 查看
leetcode代码已经放入github:[]https://github.com/gaohongbin/leetcode](https://github.com/gaohongbin/leetcode)
题目:Given an integer, write a function to determine if it is a power of two.
翻译:给你一个整型,写一个函数来确定它是否是2的幂。
思路:(1)这个题如果用一直对2取模,再除以2,看最后能不能等于1。
这个思路写下来在leetcode上会超时。
(2)根据位运算,如果一个数是2的幂,那么它的二进制表示中只有一位是1,其他全是0。
而(N&(N-1))就是把N的二进制表示的最右边一位1变为0.
所以如果一个数N是2的幂,则(N&(N-1))==0.
代码:
题目:Given an integer, write a function to determine if it is a power of two.
翻译:给你一个整型,写一个函数来确定它是否是2的幂。
思路:(1)这个题如果用一直对2取模,再除以2,看最后能不能等于1。
这个思路写下来在leetcode上会超时。
(2)根据位运算,如果一个数是2的幂,那么它的二进制表示中只有一位是1,其他全是0。
而(N&(N-1))就是把N的二进制表示的最右边一位1变为0.
所以如果一个数N是2的幂,则(N&(N-1))==0.
代码:
public boolean isPowerOfTwo(int n) { return n > 0 && ((n & (n - 1)) == 0 ); }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解