【LeetCode】Power of Two 解题报告

来源:互联网 发布:用java开发apk的步骤 编辑:程序博客网 时间:2024/05/16 14:51

Power of Two

[LeetCode]

https://leetcode.com/problems/power-of-two/

Total Accepted: 71172 Total Submissions: 194399 Difficulty: Easy

Question

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

Ways

和刚才那个是否为3的倍数好像。嗯。刚才有个字符串的方法没讲。这里试了一下。

方法一

这个方法应该是通用的方法,转换为特定的进制的字符串,然后判断是否为1开头的字符。

The code above converts number into base base and returns the result as a String. For example, Integer.toString(5, 2) == “101” and Integer.toString(5, 3) == “12”.

boolean matches = myString.matches("123");public class Solution {    public boolean isPowerOfThree(int n) {        return Integer.toString(n, 2).matches("^10*$");    }}

AC:20ms

效率肯定很慢。

方法二

还记得那个 n&(n-1) 的方法来数一个数里边有多少个1吗?没错,只要只有一个1就好。

public class Solution {    public boolean isPowerOfTwo(int n) {        if(n<=0) return false;        return (n & (n-1)) == 0;    }}

AC:2ms

方法三

嗯。参考了3的幂的另一种解法,用满足条件的最大的int来看这个n能否整除。本来想手算2的最大的幂的int是多少呢,后来一想可以用位移运算。太聪明了。恩。

public class Solution {    public boolean isPowerOfTwo(int n) {        if(n<=0) return false;        return (1<<31) % n == 0;    }}

AC:2ms

感觉最良好的一次,一口气写了三个方法。哈哈哈。

Date

2016/5/1 17:10:28

0 0
原创粉丝点击