leet-code/src/main/java/leetcode/editor/cn/PowerOfTwo.java
huangge1199@hotmail.com 1fc960edf9 231:2 的幂
2021-05-30 21:23:12 +08:00

74 lines
1.2 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//给你一个整数 n请你判断该整数是否是 2 的幂次方。如果是,返回 true ;否则,返回 false 。
//
// 如果存在一个整数 x 使得 n == 2x ,则认为 n 是 2 的幂次方。
//
//
//
// 示例 1
//
//
//输入n = 1
//输出true
//解释20 = 1
//
//
// 示例 2
//
//
//输入n = 16
//输出true
//解释24 = 16
//
//
// 示例 3
//
//
//输入n = 3
//输出false
//
//
// 示例 4
//
//
//输入n = 4
//输出true
//
//
// 示例 5
//
//
//输入n = 5
//输出false
//
//
//
//
// 提示:
//
//
// -231 <= n <= 231 - 1
//
//
//
//
// 进阶:你能够不使用循环/递归解决此问题吗?
// Related Topics 位运算 数学
// 👍 362 👎 0
package leetcode.editor.cn;
//231:2 的幂
class PowerOfTwo{
public static void main(String[] args) {
//测试代码
Solution solution = new PowerOfTwo().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public boolean isPowerOfTwo(int n) {
return n > 0 && Integer.bitCount(n) == 1;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}