LeetCode power of 2

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

Example 1:

Input: 1
Output: true 
Explanation: 20 = 1

Example 2:

Input: 16
Output: true
Explanation: 24 = 16

Example 3:

Input: 218
Output: false
class Solution {
    public boolean isPowerOfTwo(int n) {
        
        if(n<0){
            return false;
        }
        System.out.println(n);
        if(n==0){
            return false;
        }
        
        //boolean flag = false;
        int res; 
        while (n >=2){
            res = n%2;
            
            if(res !=0){
                return false;
            }
            n = n/2;
 
        }
        return true;
        
    }
}

 

posted @ 2020-06-09 14:28  CodingYM  阅读(131)  评论(0编辑  收藏  举报