結果

問題 No.353 ヘイトプラス
ユーザー spaciaspacia
提出日時 2016-06-02 14:28:58
言語 Java21
(openjdk 21)
結果
AC  
実行時間 130 ms / 1,000 ms
コード長 1,691 bytes
コンパイル時間 3,486 ms
コンパイル使用メモリ 80,684 KB
実行使用メモリ 56,204 KB
最終ジャッジ日時 2023-09-12 00:44:09
合計ジャッジ時間 5,555 ms
ジャッジサーバーID
(参考情報)
judge15 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 123 ms
56,024 KB
testcase_01 AC 126 ms
56,132 KB
testcase_02 AC 125 ms
56,144 KB
testcase_03 AC 125 ms
56,148 KB
testcase_04 AC 126 ms
56,204 KB
testcase_05 AC 125 ms
55,940 KB
testcase_06 AC 124 ms
55,888 KB
testcase_07 AC 124 ms
55,836 KB
testcase_08 AC 130 ms
55,824 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

package yukicoder;

import java.util.Arrays;
import java.util.Scanner;

public class No353 {

	public static void main (String[] args) {

		Scanner sc = new Scanner(System.in);
		int a = sc.nextInt();
		int b = sc.nextInt();

		System.out.println(add(a, b));

		sc.close();

	}

	// a足すbを計算する
	public static int add (int a, int b) {

		String a_plus_b_bin = "";

		// aとbをそれぞれ2進数に
		String a_bin = Integer.toBinaryString(a);
		String b_bin = Integer.toBinaryString(b);

		// 足し算した際の繰り上がりの有無
		boolean is_move_up = false;

		// 文字列の長さを合わせる
		while (a_bin.length() < b_bin.length()) a_bin = "0".concat(a_bin);
		while (a_bin.length() > b_bin.length()) b_bin = "0".concat(b_bin);

		for (int i = a_bin.length() - 1; i >= 0; i--) {
			a_plus_b_bin = aPlusBBinSingleDigit(a_bin.charAt(i), b_bin.charAt(i), is_move_up).concat(a_plus_b_bin);
			is_move_up = isNextMoveUp(a_bin.charAt(i), b_bin.charAt(i), is_move_up);
		}

		// 最後に繰り上がりがあったら1を付加
		if (is_move_up) a_plus_b_bin = "1".concat(a_plus_b_bin);

		return Integer.parseInt(a_plus_b_bin, 2);

	}

	// 2進数aとbの1桁単位の足し算を行い、1の位を求める
	public static String aPlusBBinSingleDigit (char a, char b, boolean is_move_up) {
		if ((a == '1') ^ (b == '1') ^ is_move_up)
			return "1";
		else
			return "0";
	}

	// 2進数aとbの1桁単位の足し算を行い、繰り上がりが起きるかを判定
	public static boolean isNextMoveUp(char a, char b, boolean is_move_up) {
		int[] bins = {a - '0', b - '0', is_move_up ? 1 : 0};
		Arrays.sort(bins);
		return bins[1] == 1 && bins[2] == 1;
	}

}
0