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

    新情况:

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

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

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

    源代码

     package HomeTest;
     
     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("F:\JAVA\testdemo\homeTest\src\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);
         }
     }

    结果截图

    当存在非法字符时

     思路

    大体功能与前一个相同,主要是添加文件读取以及用BigInteger来代替int

  • 相关阅读:
    Auto Complete with Redis
    老男孩 movie
    e人e本
    邀请大家使用dropbox
    mac Espresso
    it网站
    To Trie or not to Trie – a comparison of efficient data structures
    [转载]提高Python程序的运行速度_李小红_新浪博客
    TSTTernary Search TreeCreating An English Dictionary for lookup and spell checking | CracktheInterview
    平衡二叉搜索树
  • 原文地址:https://www.cnblogs.com/best-hym/p/12367763.html
Copyright © 2011-2022 走看看