ABC226のA,B問題をJavaで解きました。(C問題は難しくて解けませんでした)
備忘録としてまとめておきます。
A問題『Round decimals』
問題ページ:A - Round decimals
X:小数点第三位までの実数
X を小数第一位で四捨五入して得られる整数を出力する
小数点を持つ実数は、「Double型」で宣言します。
宣言(入力値を取得)した変数をroundメソッドを用いて、小数第一位で四捨五入します。
コード
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
// 画面入力値を取得する
double scanD = sc.nextDouble();
//小数第一位で四捨五入
System.out.println(Math.round(scanD));
}
}
B問題『Counting Arrays』
問題ページ:B - Counting Arrays
入力例より、数列 $a_i,_j$を$N$個取得し、取得した数列のうち重複を除く数を出力します。
重複を除くリストの取得方法として、HashSetを使用しました。
(参考サイト参照)
コード
import java.util.*;
public class Main {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//数列の数を取得する
final int N = sc.nextInt();
int[] L = new int[N];
//重複を除くリストを宣言する
Set<List<Integer>> list = new HashSet<>();
for (int i = 0; i < N; i++)
{
//数列の要素の個数を取得する (1,2)⇒要素数:2
L[i] = Integer.parseInt(sc.next());
//数列を取得する
List<Integer> k = new ArrayList<>();
for (int j = 0; j < L[i]; j++)
{
k.add(Integer.parseInt(sc.next()));
}
list.add(k);
}
//リストの重複を除いた数を出力する
System.out.println(list.size());
}
}
参考サイト
A問題:Java 四捨五入するサンプル(round)
B問題:【Java】HashSetの使い方(順序なしSet)