[英]what is the best way to solve the big number string to long?
I am working with a problem.The following code works for small string but in this case I have to work with long numbers.what could be the best possible solution ? 我正在解决一个问题。以下代码适用于小字符串,但在这种情况下,我必须使用长数字。什么是最好的解决方案?
it gives error for very long string so how to approach to solve the best possible way. 它会给很长的字符串带来错误,因此如何解决最佳方法。 by the way it is UVA424.
顺便说一句是UVA424。 There are so many solution online .I like to solve my way so it is a portion of the code
在线上有很多解决方案。我喜欢解决自己的问题,因此它是代码的一部分
import java.util.Scanner;
public class IntegerInquiry {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
long total = 0;
while (input.hasNext()) {
String i = input.next();
if(i.equals("0")) break;
int size = i.length();
if(size <=100 ){
long a = Long.parseLong(i);
total = total+a;
}
}
System.out.println(total);
}
}
For big numbers you can use BigDecimal
对于大数字,您可以使用
BigDecimal
Scanner input = new Scanner(System.in);
BigDecimal bigDecimal = new BigDecimal(0);
while (input.hasNext()) {
String i = input.next();
if (i.equals("0"))
break;
bigDecimal = bigDecimal.add(new BigDecimal(i));
}
input.close();
System.out.println("BigDecimal " + bigDecimal);
System.out.println("Long " + bigDecimal.longValue()); // caution - narrowing
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.