【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
- LeetCode-Power of Two-解题报告
- [leetcode] 231. Power of Two 解题报告
- 【LeetCode】Power of Two 解题报告
- LeetCode 231. Power of Two 解题报告
- [Leetcode] 231. Power of Two 解题报告
- leetcode解题报告233——Power of Two
- [leetcode] 326. Power of Three 解题报告
- 326. Power of Three LeetCode解题报告
- [leetcode] 342. Power of Four 解题报告
- 【LeetCode】Power of Three 解题报告
- 【LeetCode】Power of Four 解题报告
- leetcode 342. Power of Four 解题报告
- LeetCode 326. Power of Three 解题报告
- leetcode解题报告-342. Power of Four
- [Leetcode] 326. Power of Three 解题报告
- [Leetcode] 342. Power of Four 解题报告
- 【LeetCode】Intersection of Two Arrays 解题报告
- [LeetCode] Power of Two
- LeetCode 89. Gray Code(生成格雷码)
- 得到格式化的时间
- Android Studio NDk调试(基于gradle-experimental插件与LLDB)
- Codeforces 667D World Tour (最短路+枚举)
- 【周总结】——收拾行囊
- 【LeetCode】Power of Two 解题报告
- Marklogic学习 由浅入深(7)—— Marklogic应用开发指引
- android 5.x—Tinting着色和Clipping裁剪
- linux shell命令行选项与参数用法详解
- LeetCode|Word Pattern
- Volley框架的使用介绍
- Codeforces 667C Reberland Linguistics【DFS】
- 安卓java.lang.IllegalStateException: The specified child already has a parent.解决方案
- 《Vehicle Detection in High-Resolution Aerial Images Based on Fast Sparse Representation ...》论文笔记