LeetCode-两个结构分别遍历,然后合并
生活随笔
收集整理的這篇文章主要介紹了
LeetCode-两个结构分别遍历,然后合并
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
今天做了leetcode67題,兩個2進制數相加,回想了一下其實有很多這種類型的題,比如leetcode2兩數相加。
在做這種題時我自己的思路就是先循環遍歷一個短的,然后跳出循環,判斷是哪個結束,再接著合并。比如67題如下:
給定兩個二進制的字符串,比如a=”11“,b=”1“,返回結果”100“。
string addBinary(string a, string b) {int pos_a = a.size() -1;int pos_b = b.size() -1;int length = max(a.size(), b.size())+1;string result(length,' ');int add = 0;int i = length - 1;//從后向前遍歷,直到一個string用完for ( ; i >= 0; i--) {if (-1 == pos_a || -1 == pos_b)break;//有進位的情況if (a[pos_a] + b[pos_b] + add - '0' - '0'>= 2) {result[i] = (a[pos_a] -'0' + b[pos_b] - '0'+ add)%2 + '0';add = 1;}else{result[i] = (a[pos_a] - '0' + b[pos_b] - '0' + add) + '0';add = 0;}pos_a--;pos_b--;}//如果兩個都用完if (-1 == pos_a && -1 == pos_b) {if (add == 0)result.erase(0, 1);elseresult[0] = '1';return result;}//如果只有a用完if (-1 == pos_a) {while (pos_b != -1) {result[i--] = (b[pos_b] -'0'+ add)%2 + '0';add = (b[pos_b--] + add - '0')/2 ;}if (add == 1)result[0] = '1';elseresult.erase(0,1);}else{//如果只有b用完while (pos_a != -1) {result[i--] = (a[pos_a]-'0' + add) % 2+'0';add = (a[pos_a--] + add - '0') / 2 ;}if (add == 1)result[0] = '1';elseresult.erase(0, 1);}return result; } 67的復雜解法這使得代碼再跳出第一次循環后還需要做很多的工作,而且一不小心還會因為邊界條件出錯,所以需要尋找一個更加簡潔的方法來處理這種問題,尋找leetcode中這種題,多練習一下。
string addBinary(string a, string b) {string result = "";int pos_a = a.size() - 1;int pos_b = b.size() - 1;int add = 0;while (pos_a != -1 || pos_b != -1 || add == 1) {if (pos_a != -1)add += a[pos_a--] - '0';if (pos_b != -1)add += b[pos_b--] - '0';result = char(add % 2 + '0') + result;add = add/2;}return result; } 67的簡便寫法上面這種方式代碼要簡潔很多而且也不容易寫錯,注意char和string可以直接進行拼接。
?
在考慮leetcode2,兩數相加問題。
同樣是使用和上述一樣的方法
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {int add = 0;ListNode result(-1);ListNode* pos = &result;while (l1 != NULL || l2 != NULL || add != 0) {if (l1 != NULL) { add += l1->val; l1 = l1->next; }if (l2 != NULL) { add += l2->val; l2 = l2->next; }ListNode *temp = new ListNode(add % 10);pos->next = temp;pos = pos->next;add = add / 10;}return result.next; } 2的簡便解法?
轉載于:https://www.cnblogs.com/likaiming/p/8716184.html
總結
以上是生活随笔為你收集整理的LeetCode-两个结构分别遍历,然后合并的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C# 调用颜色的RGB值_RGB颜色转换
- 下一篇: 20172310 2017-2018-2