leetcode1120,LeetCode:Add Binary

 2023-10-21 阅读 31 评论 0

摘要:題目鏈接 Given two binary strings, return their sum (also a binary string). leetcode1120。For example, a = "11" b = "1" Return "100". 分析:簡單的處理二進制求和和進位即可??????????????????????????????????????? 本文地址

題目鏈接

Given two binary strings, return their sum (also a binary string).

leetcode1120。For example,
a = "11"
b = "1"
Return "100".


分析:簡單的處理二進制求和和進位即可??????????????????????????????????????? 本文地址

class Solution {
public:string addBinary(string a, string b) {int ia = a.size() - 1, ib = b.size() - 1;char carry = '0';string &res = (ia > ib)? a : b;int i = (ia > ib)? ia : ib;while(ia >= 0 && ib >= 0){char tmp = carryBit(a[ia], b[ib], carry);res[i--] = charBitAdd(charBitAdd(a[ia--], b[ib--]), carry);carry = tmp;}while(i >= 0){char tmp = carryBit(res[i], carry);res[i] = charBitAdd(res[i--], carry);carry = tmp;}if(carry == '0')return res;else return "1"+res;}
public://求和函數char charBitAdd(char a, char b){if(a == b)return '0';else return '1';}//求進位char carryBit(char add1, char add2, char carry = '0'){if((add1 == '1' && add2 == '1') ||(add1 == '1' && carry == '1') ||(add2 == '1' && carry == '1'))return '1';else return '0';}
};

?

leetcode 5?【版權聲明】轉載請注明出處:http://www.cnblogs.com/TenosDoIt/p/3475306.html

轉載于:https://www.cnblogs.com/TenosDoIt/p/3475306.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/155762.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息