LeetCode 231,326,342 --Power of Two & Three & Four

来源:互联网 发布:ug编程模具 编辑:程序博客网 时间:2024/05/17 07:53

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

Two:这几个题,都可以用同一种解法,用当前数一直整除另一个数,一旦无法整除,且余数不为0;则说明不是 2& 3& 4的幂:

<span style="font-size:14px;">public class Solution {    public boolean isPowerOfThree(int n) {        if(n <= 0) return false;        while(n % 3 == 0){            n = n/3;        }        return n == 1;    }}</span>

2的幂的另一种解法,减一相与法,如果一个数与减1想与为0 ,则是2的幂数。

<span style="font-size:14px;">public class Solution {    public boolean isPowerOfTwo(int n) {        return (n & (n-1)) == 0 && n > 0;    }}</span>


0 0
原创粉丝点击