LoginSignup
0
0

More than 1 year has passed since last update.

paiza Bランクレベルアップメニュー 「足すか掛けるか」

Posted at

paizaのBランクレベルアップメニュー「足すか掛けるか」問題に対して自分なりに
考えて書いた回答が合っていたので記念に残す。

問題は
2つの整数の組がn個与えられるので、各組の計算結果を足し合わせたものを
出力してください。
各組の計算結果は次の値です。
・2つの整数の組を足し合わせたもの
・ただし、2つの整数が同じ値だった場合は、掛け合わせたもの

入力は以下のフォーマットで与えられます。

n
a_1 b_1
...
a_n b_n

nは与えられる整数の組の行数です。
a_iとb_iはそれぞれが整数です。

私の回答

myanswer
import java.util.*;


public class Main {
    public static void main(String[] args) {
        // 自分の得意な言語で
        // Let's チャレンジ!!
        Scanner sc = new Scanner(System.in);
        int time = sc.nextInt();
        int sum = 0;
        int esum;
        for(int i = 0;i < time *2 ;i = i + 2){
        int a = sc.nextInt();
        int b = sc.nextInt();
            if(a == b){
            esum = a * b;
            } else {
            esum = a + b;
            }
        sum = sum + esum;
        }
        System.out.println(sum);
    }
}

模範解答は配列を作って操作するもので配列が理解できていないと
書きようがないものだったのでこれも残しておく。

answer
import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int times = scanner.nextInt();
        long sum = 0;

        for (int i = 0; i < times; i++) {
            long tmp[] = new long[2];
            tmp[0] = scanner.nextInt();
            tmp[1] = scanner.nextInt();

            if (tmp[0] != tmp[1]) {
                sum += (tmp[0] + tmp[1]);
            } else {
                sum += (tmp[0] * tmp[1]);
            }
        }

        System.out.println(sum);

        scanner.close();
    }
}

おしまい

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0