จากสองสตริงที่มีเลขฐานสอง เราต้องหาผลลัพธ์ที่ได้จากการเพิ่มสตริงไบนารีสองตัวนั้นแล้วส่งคืนผลลัพธ์เป็นสตริงไบนารี
เลขฐานสองคือตัวเลขที่แสดงเป็น 0 หรือ 1 ในขณะที่บวกเลขฐานสอง 2 ตัว มีกฎการบวกเลขฐานสองซึ่งต้องดูแล
0+0 → 0 0+1 → 1 1+0 → 1 1+1 → 0, carry 1

ป้อนข้อมูล
str1 = {“11”}, str2 = {“1”} ผลผลิต
“100”
ป้อนข้อมูล
str1 = {“110”}, str2 = {“1”} ผลผลิต
“111”
แนวทางที่ใช้ด้านล่างมีดังต่อไปนี้ในการแก้ปัญหา
-
ข้ามทั้งสตริงจากสุดท้าย
-
บวกเลขฐานสองของตัวเลขสองตัว
-
หากมี 1 สองตัว ให้ทำให้มันเป็นศูนย์และยก 1
-
ส่งคืนผลลัพธ์
อัลกอริทึม
Start Step 1→ declare function to add two strings string add(string a, string b) set string result = "" set int temp = 0 set int size_a = a.size() – 1 set int size_b = b.size() – 1 While (size_a >= 0 || size_b >= 0 || temp == 1) Set temp += ((size_a >= 0)? a[size_a] - '0': 0) Set temp += ((size_b >= 0)? b[size_b] - '0': 0) Calculate result = char(temp % 2 + '0') + result Set temp /= 2 Set size_a— Set size_b— End return result Step 2→ In main() Declare string a = "10101", b="11100" Call add(a, b) Stop
ตัวอย่าง
#include<bits/stdc++.h>
using namespace std;
//function to add two strings
string add(string a, string b){
string result = "";
int temp = 0;
int size_a = a.size() - 1;
int size_b = b.size() - 1;
while (size_a >= 0 || size_b >= 0 || temp == 1){
temp += ((size_a >= 0)? a[size_a] - '0': 0);
temp += ((size_b >= 0)? b[size_b] - '0': 0);
result = char(temp % 2 + '0') + result;
temp /= 2;
size_a--; size_b--;
}
return result;
}
int main(){
string a = "10101", b="11100";
cout<<"sum of strings are : "<<add(a, b);
return 0;
} ผลลัพธ์
หากรันโค้ดด้านบน มันจะสร้างผลลัพธ์ต่อไปนี้ -
sum of strings are : 110001