[231] Power of Two
来源:互联网 发布:linux查看svn版本号 编辑:程序博客网 时间:2024/05/02 10:28
1. 题目描述
Given an integer, write a function to determine if it is a power of two.
求一个整数是不是2的n次方
2. 解题思路
首先想到的是log2(2^n) = n,那么只要求该整数的对数是否是一个整数即可确定该整数k是否为2^n,但是java给定的Math函数中只有以e为底k的对数,没有直接求以m为底k的对数的函数,所以使用了换底公式转换logm(k) = log(k)/log(m),如Code1,但因为log2并不是一个整数,所以在做除法的时候会出现一定的精度损失,这种方法就无法实施了。于是我们使用第二种方法,2的n次方也就是n个2相乘,也就代表k除以2取余等于0,且除到最后得到的结果为1。比如举一个不满足要求的结果12/2=6余0,6/2=3余0,3/2=1余1。
做了后面的题发现使用log10代替log可以规避这个精度问题,具体原因未明。
另外得知了一种新的方法,因为他是一个整型,且很容易的可以被看做一个二进制数,当一个数是2的n次方时,使用二进制表示为m=16=10000(n=4),那么m-1=15=01111,那么这两个数按位与等于0,而其他的数字则没有这个特性,如m=18=10010 m-1=17=10001,按位与为10000。需注意2的0次方算不算。
3. Code
// Code1(Failed)public class Solution { //当n = 536870912时,精度出现问题 public boolean isPowerOfTwo(int n) { double result = Math.log(n) / Math.log(2); int i = (int)result; return (result - i) == 0; // 判断result是不是整数 }}
// Code2(Accept)public class Solution { public boolean isPowerOfTwo(int n) { if (n == 0) return false; // n取余2为0 while(n%2 == 0) { n = n/2; } if (n == 1) return true; return false; }}
// Code3public class Solution { public boolean isPowerOfTwo(int n) { // 如果n=0返回false,else返回n按位与n-1 // 10000 & 01111 = 0 return n == 0 ? false : n & (n-1) == 0; }}
0 0
- 231Power of Two
- 231 Power of Two
- 231Power of Two
- 231 - power of two
- 231Power of Two
- 231 Power of Two
- 231:Power of Two
- [231]Power of Two
- 231 Power of Two
- Power of Two---231
- [231] Power of Two
- leetcode-231 Power of Two
- leetcode 231:Power of Two
- LeetCode 231: Power of Two
- 231-e-Power of Two
- leetcode 231: Power of Two
- leetcode[231]:Power of Two
- Power of Two(leetcode 231)
- 记录学习gitbook的相关
- 拓扑排序
- 数据库概述(一)
- 高性能JDBC连接池:HikariCP
- centos 6升级Python2.7安装pip
- [231] Power of Two
- emWin实现BMP位图皮肤之Progbar篇
- 红米刷机之往回刷
- willMoveToParentViewController和didMoveToParentViewController
- 2833 奇怪的梦境
- struts2文件上传
- APP开发实战65-应用级别的BaseActivity设计
- ConnectionResetError: [Errno 104] Connection reset by peer
- 做个图片的防盗链