文件存取,大数计算
public class array2 { public static void putin() { } public static void main(String age[]) { Scanner scan=new Scanner(System.in); int max=2; //数组大小 int i; //循环 String a1[]=new String[max]; //数组初始化String BigInteger a[]=new BigInteger[max]; for(i=0;i<max;i++) { System.out.println("输入整数:"); if(scan.hasNextBigInteger()) { // 判断输入的是否是整数 BigInteger mid=scan.nextBigInteger(); a1[i]=String.valueOf(mid); System.out.println( a1[i]); //输出显示 } } scan.close();
try { FileOutputStream file=new FileOutputStream("E:\\java\\test222\\src\\test222\\array.txt"); DataOutputStream out=new DataOutputStream(file); for(i=0;i<max;i++) { out.writeUTF(a1[i]); } out.close(); }catch(IOException e) { } try { FileInputStream file=new FileInputStream("E:\\java\\test222\\src\\test222\\array.txt"); DataInputStream in=new DataInputStream(file); try { i=0; while(true) { String n1=in.readUTF(); //System.out.println(n1); a[i]=new BigInteger(n1); i++; } }catch(EOFException e) { in.close(); } }catch(IOException e) { } int x,y; BigInteger maximum=new BigInteger("0"); //最大值 BigInteger ad; //每次相加之和 BigInteger mid; //中间比较 for(x=0;x<max;x++) { ad=new BigInteger("0"); mid=a[x]; for(y=x;y<max;y++) { ad=ad.add(a[y]); if(ad.compareTo(mid)==1) { mid=ad; } } if(mid.compareTo(maximum)==1) maximum=mid; } System.out.println(maximum); }
以上步骤包括:使用scanner接受键盘输入,判断整数,转换成String存入txt文件,从文件读取并存入BigInteger数组,使用O(n*2)算法,取得连续子数组的最大值。
其中,向TXT文件存取利用了FileInputStream和FileOutputStream,而大数的运算建立在BigInteger的基础上,以下是常用的BigInteger的方法:
BigInteger a=new BigInteger("0");初始化
a.add(b);加法
subtract(); 减法
multiply(); 乘法
divide(); 相除取整数
remainder(); 取余
abs(); 绝对值

浙公网安备 33010602011771号