java int is取前两位_Java Guava IntMath isPowerOfTwo()用法及代码示例

Guava IntMath类的isPowerOfTwo()方法用于检查数字是否为2的幂。它接受要检查的数字作为参数,并根据数字是否为2的幂返回布尔值true或false。

用法:

public static boolean isPowerOfTwo(int x)

参数:此方法接受单个参数x,该参数为整数类型。

返回值:如果x代表2的幂,则该方法返回true;如果x代表2的幂,则该方法返回false。

异常:该方法没有任何异常。

注意:这与Integer.bitCount(x)== 1不同,因为Integer.bitCount(Integer.MIN_VALUE)== 1,但Integer.MIN_VALUE不是2的幂。

范例1:

// Java code to show implementation of

// isPowerOfTwo(int x) method of Guava's

// IntMath class

import java.math.RoundingMode;

import com.google.common.math.IntMath;

class GFG {

// Driver code

public static void main(String args[])

{

int a1 = 63;

// Using isPowerOfTwo(int x) method

// of Guava's IntMath class

if (IntMath.isPowerOfTwo(a1))

System.out.println(a1 + " is power of 2");

else

System.out.println(a1 + " is not power of 2");

int a2 = 1024;

// Using isPowerOfTwo(int x) method

// of Guava's IntMath class

if (IntMath.isPowerOfTwo(a2))

System.out.println(a2 + " is power of 2");

else

System.out.println(a2 + " is not power of 2");

}

}

输出:

63 is not power of 2

1024 is power of 2

范例2:

// Java code to show implementation of

// isPowerOfTwo(int x) method of Guava's

// IntMath class

import java.math.RoundingMode;

import com.google.common.math.IntMath;

class GFG {

// Driver code

public static void main(String args[])

{

int a1 = 10;

// Using isPowerOfTwo(int x) method

// of Guava's IntMath class

if (IntMath.isPowerOfTwo(a1))

System.out.println(a1 + " is power of 2");

else

System.out.println(a1 + " is not power of 2");

int a2 = 256;

// Using isPowerOfTwo(int x) method

// of Guava's IntMath class

if (IntMath.isPowerOfTwo(a2))

System.out.println(a2 + " is power of 2");

else

System.out.println(a2 + " is not power of 2");

}

}

输出:

10 is not power of 2

256 is power of 2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值