简体   繁体   English

解决大数字字符串变长的最佳方法是什么?

[英]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.

相关问题 ModelMapper:解决此问题的最佳方法是什么 - ModelMapper: What is the best way to solve this 分页大结果集的最佳方法是什么-Java - what is best way to paging big Resultset -Java 在 Hibernate 中将长列转换为字符串的最佳方法 - Best way to convert long column to String in Hibernate 将String类型的HashSet转换为Long类型的HashSet的最佳/有效方法是什么? - What is the best/efficient way to convert HashSet of type String to HashSet of type Long 在Java中将List <Long>对象转换为long []数组的最佳方法是什么? - What is the best way of converting List<Long> object to long[] array in java? 将大十进制格式转换为美元格式的最佳方法是什么? - What is the best way to format a big decimal into dollar form? 在Intellij中的大项目中重新排列文件的最佳方法是什么? - What is the best way to rearrange files in a big project in Intellij? 在Java中以美分(整数)转换美元(大十进制)的最佳方法是什么? - What is the best way to convert Dollars (Big Decimal) in Cents (Integer) in java? 从Web服务返回大块二进制数据的最佳方法是什么? - What is the best way to return big chunks of binary data from a webservice? 将大字节字符串写入文件的最佳有效方法 - Best efficient way to write a big string of bytes to file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM