如何在Java中存储1e100这样的数字(类似Python示例)?

huangapple go评论80阅读模式
英文:

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 &lt;= N &lt;= 1e100

Same in Python code:

n=int(input())
if(n!=0 and (n&amp;(n-1)==0)):
    print(&quot;yes&quot;)
else:
    print(&quot;no&quot;)

答案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) &amp;&amp; n.and(n.subtract(BigInteger.ONE)).equals(BigInteger.ZERO)){
   System.out.println(&quot;yes&quot;);
} else {
   System.out.println(&quot;no&quot;);
}

Demo!

答案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(&quot;1267650600228229401496703205376&quot;);
if (isPowerOf2(integer)) System.out.println(&quot;yarp&quot;);
else System.out.println(&quot;nope&quot;);

huangapple
  • 本文由 发表于 2020年7月25日 22:08:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/63089333.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定