博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Power of Two & Power of Three & Power of Four
阅读量:4922 次
发布时间:2019-06-11

本文共 1342 字,大约阅读时间需要 4 分钟。

 Check Power of 2

Using O(1) time to check whether an integer n is a power of 2.

Example

For n=4, return true;

For n=5, return false;

奇数总是有超过2个1.

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

 Check Power of 3

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

Follow up:

Could you do it without using any loop / recursion?

1 public class Solution { 2     public boolean isPowerOfThree(int n) { 3         if (n == 0)    return false; 4  5         if (n == 1) return true; 6  7         if (n > 1) 8             return n % 3 == 0 && isPowerOfThree(n / 3); 9         else10             return false;11     }12 }

Check Power of 4

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Example:

Given num = 16, return true. Given num = 5, return false.

1 private boolean smartBit(long num){2     return (num > 0) && ((num & (num - 1)) == 0) && ((num & 0x5555555555555555l) == num);3 }

 Explanation:

The magic numbers might seem very confusing. But they are not random (obviously!). Let us start with 0X55555555. Binary representation of 5 is 0101. So 0X55555555 has 16 ones, 16 zeros and the ones,zeros take alternate positions.

转载于:https://www.cnblogs.com/beiyeqingteng/p/5697737.html

你可能感兴趣的文章
ScrollView嵌套GridView和ListView行高问题
查看>>
测试秒杀新版本3.5 stieserver cms
查看>>
Lua获取当前时间
查看>>
redis5.0主从配置
查看>>
JavaScript严谨模式(Strict Mode)提升开发效率和质量
查看>>
[洛谷P4092][HEOI2016/TJOI2016]树
查看>>
nginx配置比较杂乱的总结
查看>>
docker 真实---安装基本映像 (一)
查看>>
php中使用array_slice将数组中的元素分类
查看>>
关于C#的partial修饰符
查看>>
哨兵元素的应用总结
查看>>
关于Request.PathInfo
查看>>
fiddler抓手机报文的配置指南
查看>>
Linux/CentOS下修改MAC地址
查看>>
Centos7下yum安装mongodb
查看>>
Vmware Tools is currently being installed on your system(转)
查看>>
scroll家族中的scrollWidth 和 scrollHeight
查看>>
mysql5.7忘记密码修改方法
查看>>
poj 1251续
查看>>
fmt 包中的函数和方法
查看>>