在C++中新增兩個二進位制字串的程式
給定兩個二進位制數字字串,我們需要找到透過將這兩個二進位制字串相加而得到的結果並返回結果作為二進位制字串。
二進位制數是指表示為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,則將其變為0並進位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
廣告