0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Paizaの問題解いてたら、足し算をゴリ押しするより論理演算使ったほうがカッコいいじゃんって気づきました。


📝 問題概要

01 の整数 A , B が与えられる。

A + B の2進表記で

下から2桁目 → C(Carry:繰り上げ)

下から1桁目 → S(Sum:和)

を出力せよ!

例:

入力: 
1 1

出力: 
1 0


例1:普通に足し算

const sum = A + B;
const S = sum % 2;
const C = Math.floor(sum / 2);
console.log(C, S);
  • sum = A + B として普通に足し算する
  • Sは 1の位 を sum % 2 で求める
  • Cは 繰り上がりを Math.floor(sum / 2) で求める

たしかに動くけど、なんか...スマートさに欠ける!


✅例2:論理演算

const C = A & B; // AND: 両方1なら1
const S = A ^ B; // XOR: 違うときだけ1
console.log(C, S);
  • &(AND) は 「両方が1なら1」 → 繰り上がり(Carry)が発生する条件
  • ^(XOR) は 「どちらか一方が1なら1」 → その桁の合計(Sum)の値


✍️メモ まとめ

  • &(AND)は両方1なら1 → Cにぴったり。
  • ^(XOR)はどちらか一方だけ1なら1 → Sにぴったり。

これが噂の「半加算器」か…!


失敗談(´;ω;`)と解決法🐈

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?