Java在程序设计题目中的妙用

来源:互联网 发布:excel重复数据合并求和 编辑:程序博客网 时间:2024/06/05 15:35
    程序设计题目中有一类叫做大数的操作,在c++中实现这种操作比java中困难的多,java有现成的类可供使用。他们分别是BigInteger和BigDecimal,分别是大整数类和大浮点数类。都在java.math.*包中。
  1. 大整数相加
    BigInteger a=new BigInteger(“1”);
    BigInteger b=new BigInteger(“2”);
    a.add(b);

以POJ1502为例

Integer Inquiry
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 34114 Accepted: 13285
Description

One of the first users of BIT’s new supercomputer was Chip Diller. He extended his exploration of powers of 3 to go from 0 to 333 and he explored taking various sums of those numbers.
This supercomputer is great,'' remarked Chip.I only wish Timothy were here to see these results.” (Chip moved to a new apartment, once one became available on the third floor of the Lemon Sky apartments on Third Street.)
Input

The input will consist of at most 100 lines of text, each of which contains a single VeryLongInteger. Each VeryLongInteger will be 100 or fewer characters in length, and will only contain digits (no VeryLongInteger will be negative).

The final input line will contain a single zero on a line by itself.
Output

Your program should output the sum of the VeryLongIntegers given in the input.
Sample Input

123456789012345678901234567890
123456789012345678901234567890
123456789012345678901234567890
0
Sample Output

370370367037037036703703703670
Source

East Central North America 1996

import java.io.*;  import java.util.*;  //Scanner类控制控制台读入import java.math.*;  public class Main  {      public static void main(String[] args)      {          BigInteger b1,sum;          Scanner cin=new Scanner(new BufferedInputStream(System.in));          sum=new BigInteger("0");   //sum置0        while (cin.hasNext())  //类似于!=EOF        {              b1=cin.nextBigInteger();   //读取输入            if (b1.compareTo(new BigInteger("0")) == 0)    //若输入是0则结束                break;              sum=sum.add(b1);   //sum+=b1;        }          System.out.println(sum);      }  }  
1 0
原创粉丝点击