zoukankan      html  css  js  c++  java
  • 返回一个整数数组中最大子数组的和(续)

    新情况:

    1、要求数组从文件读取。

    2、如果输入的数组很大, 并且有很多大的数字, 就会产生比较大的结果 (考虑一下数的溢出), 请保证你的程序能正常输出。

    3、另外, 如果输入文件的参数有错误, 这个程序应该能正常退出, 并显示相应的错误信息。 任何输入错误都不能导致你的程序崩溃。

    一、源代码

    import java.io.*;
    import java.math.BigInteger;
    import java.util.ArrayList;
    import java.util.List;
    
    public class MaxList {
        public static void main(String[] args) throws IOException {
            BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("1.txt")));
            List<BigInteger> list = new ArrayList<>();
            String temp;
            BigInteger max = BigInteger.valueOf(Integer.MIN_VALUE);
            while ((temp = bufferedReader.readLine()) != null) {
                try {
                    BigInteger x = BigInteger.valueOf(Long.parseLong(temp));
                    System.out.println(x);
                    list.add(x);
                }catch (NumberFormatException e){
                    System.err.println("存在非法字符,退出程序!");
                    return;
                }
            }
            bufferedReader.close();
            BigInteger sum = list.get(0),zero = BigInteger.valueOf(0);
            System.out.println("-------------");
            for (int i = 1;i < list.size();i++){
                if (sum.compareTo(zero) == -1){
                    sum = list.get(i);
                }else {
                    sum = sum.add(list.get(i));
                }
                if (sum.compareTo(max) == 1){
                    max = sum;
                }
            }
            System.out.println("结果为:"+max);
        }
    }

    二、截图

     当有非法字符“a”时自动退出程序。

     无错误时正常显示信息。

    三、思路

      使用工具类---BigInteger来替代之前的int。

  • 相关阅读:
    换零钱问题
    candy
    动态规划之最长上升子序列
    宗成庆自然语言理解笔记 02 数学基础
    宗成庆自然语言理解笔记 01 绪论
    single-number
    single-number-ii
    菜鸟学开店—自带U盘的打印机
    菜鸟学开店—最简收银POS系统
    菜鸟学开店—电子称连接标签打印机
  • 原文地址:https://www.cnblogs.com/wuren-best/p/12367314.html
Copyright © 2011-2022 走看看