mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-05-09 23:51:34 +08:00
Merge pull request #1132 from akiyamaneko/patch-4
NumberUtil 增加新功能 isPowerOfTwo 判断整数是否是2的幂
This commit is contained in:
commit
d763282047
@ -2157,6 +2157,17 @@ public class NumberUtil {
|
|||||||
return number.pow(n);
|
return number.pow(n);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断一个整数是否是2的幂
|
||||||
|
*
|
||||||
|
* @param n 待验证的整数
|
||||||
|
* @return 如果n是2的幂返回true, 反之返回false
|
||||||
|
*/
|
||||||
|
public static boolean isPowerOfTwo(long n) {
|
||||||
|
return (n > 0) && ((n & (n - 1)) == 0);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 解析转换数字字符串为int型数字,规则如下:
|
* 解析转换数字字符串为int型数字,规则如下:
|
||||||
*
|
*
|
||||||
|
@ -254,4 +254,14 @@ public class NumberUtilTest {
|
|||||||
final BigDecimal mul = NumberUtil.mul(new BigDecimal("10"), null);
|
final BigDecimal mul = NumberUtil.mul(new BigDecimal("10"), null);
|
||||||
Assert.assertEquals(BigDecimal.ZERO, mul);
|
Assert.assertEquals(BigDecimal.ZERO, mul);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void isPowerOfTwoTest() {
|
||||||
|
Assert.assertEquals(false, NumberUtil.isPowerOfTwo(-1));
|
||||||
|
Assert.assertEquals(true, NumberUtil.isPowerOfTwo(16));
|
||||||
|
Assert.assertEquals(true, NumberUtil.isPowerOfTwo(65536));
|
||||||
|
Assert.assertEquals(true, NumberUtil.isPowerOfTwo(1));
|
||||||
|
Assert.assertEquals(false, NumberUtil.isPowerOfTwo(17));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user