【问题标题】:Greatest Product of Five Consecutive Digits五个连续数字的最大乘积
【发布时间】:2013-04-30 21:15:01
【问题描述】:

我正在尝试将 50 个字符的字符串对象解析为整数。我一直在尝试扫描包含 100 行(每行有 50 位数字)的数据文件并计算数字的总和。

每次我尝试将字符串解析为整数时,调用都会引发 NumberFormatException

这是我到目前为止所拥有的......

{
    long totalSum = 0;
    ArrayList<Long> list = new ArrayList<Long>();

    // Create a new JFileChooser object.
    JFileChooser fileChooser = new JFileChooser(
            "C:\\Users\\Jon\\workspace\\Project Euler\\src");

    // Create an "Open File" Dialog box for
    // the user.
    fileChooser.showOpenDialog(null);

    // Get the file the user selects.
    File inputFile = fileChooser.getSelectedFile();

    try
    {
        Scanner in = new Scanner (inputFile);

        String nextString = "";

        // If the scanner has another token to scan,
        // continue with the loop.
        while (in.hasNext())
        {
            // The next string is the next number of characters
            // that are not seperated by white space.
            nextString = in.next();

            try {

                ing nextNumber = Integer.parseInt(nextString);
                list.add(nextNumber);

            } catch (NumberFormatException e) {
                System.out.println ("NumberFormatException: " + e.getMessage());
            }

        }

        in.close();

我在尝试解析之前尝试“修剪” String 对象,但没有任何东西可以修剪。我正在扫描的行中没有任何空白。

以下是我尝试扫描并计算以下值的几行:

37107287533902102798797998220837590246510135740250 46376937677490009712648124896970078050417018260538 74324986199524741059474233309513058123726617309629

我检查了 API 并在 Stack 中进行了相当彻底的搜索。有谁知道如何解决这个问题?

【问题讨论】:

  • 我认为这些数字大于整数的大小。尝试 Long.parseLong(nextString) 但我认为您的数字仍然太大,这意味着您应该查看 BigInteger 类。你可以制作一个 BigInteger 的数组列表

标签: java parsing java.util.scanner


【解决方案1】:

您的数字太大,无法放入int,范围为-21474836482147483647。它们也太大而无法放入long,范围为-9223372036854775808L9223372036854775807L。如果它不适合数据类型的范围,则抛出 NumberFormatException

您可能想尝试将数字解析为double

double nextNumber = Double.parseDouble(nextString);

但这可能会失去一点精度。 Double 具有 53 位精度,适用于大约 16 位。 double 会丢失精度。

要保持精度,请使用BigInteger

BigInteger nextNumber = new BigInteger(nextString);

BigInteger 是任意精度,不会丢失任何精度。您可以直接在BigIntegers 之间使用基本算术和比较。

【讨论】:

  • 完美!我忽略了我正在使用的范围。感谢您的友好提醒。
猜你喜欢
  • 2014-02-27
  • 2015-12-15
  • 2021-03-09
  • 2018-05-02
  • 2020-09-18
  • 1970-01-01
  • 1970-01-01
  • 2013-12-31
  • 1970-01-01
相关资源
最近更新 更多