【LeetCode】231 Power of Two
2015-12-01 17:11
387 查看
Given an integer, write a function to determine if it is a power of two.
思路:
求是否是2的幂,由2可以联想到2进制,只要数的2进制表示中只含有一个值为1的bit位,这个数即是2的幂。
法2用Integer.bitCount(int i)方法,该方法虽然只需一行即可解决问题,但是所需的时间却比自己写的法1更多。
Integer.bitCount(int i)源码:
法1:(Run Time: 2ms)
法2:(Run Time:3ms)
思路:
求是否是2的幂,由2可以联想到2进制,只要数的2进制表示中只含有一个值为1的bit位,这个数即是2的幂。
法2用Integer.bitCount(int i)方法,该方法虽然只需一行即可解决问题,但是所需的时间却比自己写的法1更多。
Integer.bitCount(int i)源码:
public static int bitCount(int i) { // HD, Figure 5-2 i = i - ((i >>> 1) & 0x55555555); i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); i = (i + (i >>> 4)) & 0x0f0f0f0f; i = i + (i >>> 8); i = i + (i >>> 16); return i & 0x3f; }
法1:(Run Time: 2ms)
public class Solution { public boolean isPowerOfTwo(int n) { if(n <= 0){ return false; } int sum = 0; int m = 0x00000001; for(int i=0;i<32;i++){ if((n & m)!=0){ sum ++; } if(sum > 1){ return false; } m = m << 1; } return true; } }
法2:(Run Time:3ms)
public class Solution { public boolean isPowerOfTwo(int n) { if(n < 0){ return false; } return Integer.bitCount(n) == 1; } }
相关文章推荐
- 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 题解