hdu oj從1000-1001-1002

自己要開始學習java,用hdu一邊做一邊記錄下。
hdu1000
很簡單直接上代碼。

import java.util.*;

public class Main {
    public static void main(String args[])
    {
        Scanner in = new Scanner(System.in);
        while(in.hasNextInt())
        {
            int a = in.nextInt();
            int b = in.nextInt();
            System.out.println(a+b);
        }
    }

}

hdu1001
計算從1到n的累加。有倆種簡單的方法。一種直接用for循環從1到n,num= i+num;一種是n * (n+1)/2。因爲1+2+3+4……..+(n-3)+(n-2)+(n-1)+n你可以反着寫n+(n-1)+(n-2)+(n-3)+…..3+2+1;這時候呢上下相加除以2還是一樣的,但可以看做是n倍的(n+1)再除以2;但是,這裏要注意要求You may assume the result will be in the range of 32-bit signed integer. 一個在32位有符號整數的範圍內。所以n*( n+1)可能會超出32位,所以可以加一個判斷,if(n%2 == 0)判斷是不是偶數,如果是偶數的話可以改爲n/2 * (n+1),如果是奇數的話(n+1)/2 * n。

import java.util.*;

public class Main {
    public static void main(String args[])
    {
        Scanner in = new Scanner(System.in);
        while(in.hasNextInt())
        {
            int sum;
            int  n = in.nextInt();
            if(n%2 == 0)
            {
                sum = n/2*(n+1);
            }
            else
            {
                sum = (n+1)/2*n;
            }
            System.out.println(sum);
            System.out.println();
        }
    }

}

hdu 1002

大整數相加,想當年,在C語言的學習中,我們常常被灌輸,int的範圍不能超過2^32如果你的操作系統是64位的還能去到2^64,而long則是固定2^32,由於我是用java的,所以不得不提一下java中特別好用的BigInteger,這裏直接用它就可以解決。

import java.math.BigInteger;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        BigInteger a, b;
        int T;
        Scanner in = new Scanner(System.in);
        T = in.nextInt();
        for (int i = 1; i <= T; ++i) {
            System.out.println("Case" + " " + i + ":");
            a = in.nextBigInteger();
            b = in.nextBigInteger();
            if (i < T) {
                System.out.println(a + " + " + b + " = " + a.add(b) );
                System.out.println();
            }
            else {
                System.out.println(a + " + " + b + " = " + a.add(b));
            }
        }
    }
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章