ในบทความนี้ เราจะเรียนรู้วิธีบวกเลขฐานสอง (Binary) ที่เก็บเป็นสตริงในภาษา Java
ตัวอย่างการทำงาน
อินพุต:
10101 10001
เอาต์พุต:
100110
อัลกอริทึม
- เริ่มต้นโปรแกรม
- สร้าง Scanner อ่านค่า binary 2 ตัว (เก็บเป็น long)
- กำหนดตัวแปร
carry(ตัวนำ) = 0 - ใช้ลูป
whileตรวจสอบทั้งคู่ไม่เป็น 0 - คำนวณบิตแต่ละตำแหน่ง:
sum[i] = (carry + (b1%10 + b2%10)) % 2 - อัปเดต carry:
carry = (b1%10 + b2%10 + carry) / 2 - เลื่อนบิต: หารทั้งคู่ด้วย 10
- ถ้า carry เหลือ ให้เพิ่มในอาร์เรย์
- พิมพ์ผลลัพธ์ย้อนกลับ
- จบโปรแกรม
ตัวอย่างที่ 1: รับค่าจากผู้ใช้
import java.util.*;
public class AddBinaryNumbers {
public static void main(String[] args) {
long binary_input_1, binary_input_2;
System.out.println("Required packages have been imported");
Scanner input = new Scanner(System.in);
System.out.println("A reader object has been defined");
System.out.print("Enter the first binary number: ");
binary_input_1 = input.nextLong();
System.out.print("Enter the second binary number: ");
binary_input_2 = input.nextLong();
int i = 0, carry = 0;
int[] binary_sum = new int[10];
while (binary_input_1 != 0 || binary_input_2 != 0) {
binary_sum[i++] = (int) (carry + (binary_input_1 % 10 + binary_input_2 % 10) % 2);
carry = (int) ((binary_input_1 % 10 + binary_input_2 % 10 + carry) / 2);
binary_input_1 = binary_input_1 / 10;
binary_input_2 = binary_input_2 / 10;
}
if (carry != 0) {
binary_sum[i++] = carry;
}
--i;
System.out.print("\nThe sum of the binary numbers is: ");
while (i >= 0) {
System.out.print(binary_sum[i--]);
}
System.out.print("\n");
}
}
ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า
public class AddingBinaryNumbers {
public static void main(String[] args) {
long binary_input_1 = 10101, binary_input_2 = 10001;
System.out.print("The first binary number is " + binary_input_1);
System.out.print("\nThe second binary number is " + binary_input_2);
int i = 0, carry = 0;
int[] binary_sum = new int[10];
while (binary_input_1 != 0 || binary_input_2 != 0) {
binary_sum[i++] = (int) (carry + (binary_input_1 % 10 + binary_input_2 % 10) % 2);
carry = (int) ((binary_input_1 % 10 + binary_input_2 % 10 + carry) / 2);
binary_input_1 = binary_input_1 / 10;
binary_input_2 = binary_input_2 / 10;
}
if (carry != 0) {
binary_sum[i++] = carry;
}
--i;
System.out.print("\nThe sum of the binary numbers is: ");
while (i >= 0) {
System.out.print(binary_sum[i--]);
}
System.out.print("\n");
}
}
วิธีที่ง่ายกว่า: ใช้ BigInteger
import java.math.BigInteger;
String b1 = "10101", b2 = "10001";
BigInteger n1 = new BigInteger(b1, 2);
BigInteger n2 = new BigInteger(b2, 2);
BigInteger sum = n1.add(n2);
System.out.println(sum.toString(2)); // 100110
ใช้ BigInteger รองรับความยาวไม่จำกัด และเขียนโค้ดสั้นกว่ามาก