• Leetcode: Power of Two


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

    Best Solution

    1 class Solution {
    2 public:
    3     bool isPowerOfTwo(int n) {
    4         if(n<=0) return false;
    5         return !(n&(n-1));
    6     }
    7 };
    1 public class Solution {
    2     public boolean isPowerOfTwo(int n) {
    3         return n>0 && Integer.bitCount(n) == 1;
    4     }
    5 }

    还是有一个地方不小心:Integer.MIN_VALUE, 应该是false,但是因为只有一个1,我曾经判断为true。事实上,所有negative value都应该是false

     一旦符号位为1,就return false, 检查其他位只有1个1

     1 public class Solution {
     2     public boolean isPowerOfTwo(int n) {
     3         boolean flag = false;
     4         for (int i=0; i<=30; i++) {
     5             if (((n>>>i) & 1) == 1) {
     6                 if (!flag) flag = true;
     7                 else return false;
     8             }
     9         }
    10         if (((n>>>31) & 1) == 1) return false;
    11         return flag;
    12     }
    13 }

     做的时候遇到很多语法错误:

    1. “==” 优先级 比 “&” 高, “&”表达式一定要括起来

    2. >>是带符号的右移,如果是负数,高位始终补1. >>>才是无符号的右移

    这样也可以,先确认除开符号位的31位只有一个1,然后确认符号位不为1,注意一定要无符号右移,或者写成 ((n>>31)&1) != 1

    更好的方法:单独考虑符号位,一旦为1,return false

     1 public class Solution {
     2     public boolean isPowerOfTwo(int n) {
     3         boolean one = false;
     4         for (int i=0; i<31; i++) {
     5             if (((n>>i) & 1) == 1) {
     6                 if (!one) 
     7                     one=true;
     8                 else return false; 
     9             }
    10         }
    11         return one && (n>>>31)!=1; 
    12     }
    13 }
  • 相关阅读:
    深浅拷贝
    生成式、生成器、迭代对象、迭代器
    memcached
    redis安装配置
    基于docker搭建mysql主从复制架构
    centos 安装 最新版本的docker
    Linux小技巧
    神奇的'license': 'AGPL 3.0'标签报错
    新博客重新开通了
    通过linkserver不能调远程表值函数
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5060206.html
Copyright © 2020-2023  润新知