Lettcode_231_Power of Two

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/47334243


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


思路:

(1)题意为给定一个正整数,判断该正整数是否为2的幂。

(2)该题属于Lettcode中的简单题。只需循环判断正整数N对2求余是否为0,如果不为0,返回false;如果为0,则N的值为原来的一半,判断N是否为1,如果为1,则返回true,否则返回false。

(3)详情见下方代码。希望本文对你有所帮助。


算法代码实现如下:

package leetcode;

/**
 * @author liqqc
 */
public class Power_of_Two {
	public static boolean isPowerOfTwo(int n) {
		if (n == 0)
			return false;
		if (n == 1)
			return true;

		while (n != 0) {
			if (n % 2 == 0) {
				n = n / 2;
				if (n == 1)
					return true;
			} else {
				return false;
			}

		}
		return true;
	}
}

你可能感兴趣的:(java,LeetCode,算法)