英文:
How to store 1e100 number in java (like python example)?
问题
我需要输出:如果 N
是直接是 2
的幂,则输出 yes
,否则输出 no
,其中 1 <= N <= 1e100
。
同样的 Python 代码:
n = int(input())
if n != 0 and (n & (n - 1) == 0):
print("yes")
else:
print("no")
英文:
I need to output: yes
if N
is a direct power of 2
and no
otherwise, where 1 <= N <= 1e100
Same in Python code:
n=int(input())
if(n!=0 and (n&(n-1)==0)):
print("yes")
else:
print("no")
答案1
得分: 1
你可以使用 BigInteger
来存储任意大小的整数。
Scanner sc = new Scanner(System.in);
BigInteger n = new BigInteger(sc.nextLine());
if (!n.equals(BigInteger.ZERO) && n.and(n.subtract(BigInteger.ONE)).equals(BigInteger.ZERO)) {
System.out.println("yes");
} else {
System.out.println("no");
}
英文:
You can use BigInteger
to store arbitrarily large integers.
Scanner sc = new Scanner(System.in);
BigInteger n = new BigInteger(sc.nextLine());
if(!n.equals(BigInteger.ZERO) && n.and(n.subtract(BigInteger.ONE)).equals(BigInteger.ZERO)){
System.out.println("yes");
} else {
System.out.println("no");
}
答案2
得分: 1
在Java中,你必须使用BigInteger
类处理这么大的整数。这个类还有一些方便的方法来处理这个数字的二进制表示。
例如,你可以使用bitCount
方法来判断一个数字是否是2的幂次:
boolean isPowerOf2(BigInteger integer) {
return integer.bitCount() == 1;
}
用法:
var integer = new BigInteger("1267650600228229401496703205376");
if (isPowerOf2(integer)) System.out.println("yarp");
else System.out.println("nope");
英文:
In Java, you have to use the BigInteger
class for integers this big. This class also has several convenient methods to work with the binary representation of this number.
For example, you can use bitCount
to determine if number is a power of 2:
boolean isPowerOf2(BigInteger integer) {
return integer.bitCount() == 1;
}
Usage:
var integer = new BigInteger("1267650600228229401496703205376");
if (isPowerOf2(integer)) System.out.println("yarp");
else System.out.println("nope");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论