leetcode--Power of Two

来源:互联网 发布:星际淘宝网588 编辑:程序博客网 时间:2024/06/08 02:30

题目:Power of Two

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

One:以n为参数 n/2为变化率进行循环Iterable

public class Solution {    public boolean isPowerOfTwo(int n) {       if(n==1)return true;       while(n!=0){           if(n==1)return true;           if(n%2!=0)break;             n/=2;       }               return false;    }}
Two:进一步简化

public class Solution {    public boolean isPowerOfTwo(int n) {       if(n==1)return true;       while(n%2==0){             n/=2;       }        return n==1;    }}

Three:递归的方法Recursive

public class Solution {    public boolean isPowerOfTwo(int n) {       if(n==1)return true;       if(n<1||n%2 !=0)return false;        return isPowerOfTwo(n/2);    }}

Four:Recursive进一步简化

public class Solution {    public boolean isPowerOfTwo(int n) {    return n>0 && (n==1 || (n%2==0 && isPowerOfTwo(n/2)));    }}


0 0
原创粉丝点击