2013.12.22 03:31
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
Solution:
This is a problem about big integer addition, only in that it's binary. My solution is to add them up bit by bit, reverse the char array and return the result as std::string.
Time compexity is O(max(m, n)), space complexity is O(max(m, n)), where m and n are the length of two strings.
Accepted code:
1 #define __MAIN__ 2 #ifdef __MAIN__ 3 #include <string> 4 using namespace std; 5 #endif 6 7 class Solution { 8 public: 9 string addBinary(string a, string b) { 10 // Note: The Solution object is instantiated only once and is reused by each test case. 11 if(a.length() < b.length()){ 12 return addBinary(b, a); 13 } 14 15 if(a == "0"){ 16 return b; 17 }else if(b == "0"){ 18 return a; 19 } 20 21 int i; 22 char *buf = nullptr, tmp; 23 int lena, lenb; 24 25 lena = a.length(); 26 lenb = b.length(); 27 buf = new char[lena + 2]; 28 for(i = 0; i < lena + 2; ++i){ 29 buf[i] = 0; 30 } 31 for(i = 0; i < lena; ++i){ 32 buf[i] += (a[lena - 1 - i] - '0'); 33 } 34 for(i = 0; i < lenb; ++i){ 35 buf[i] += (b[lenb - 1 - i] - '0'); 36 } 37 for(i = 0; i < lena + 1; ++i){ 38 buf[i + 1] += buf[i] / 2; 39 buf[i] %= 2; 40 } 41 for(i = 0; i < lena + 1; ++i){ 42 buf[i] += '0'; 43 } 44 for(i = 0; i < lena - i; ++i){ 45 tmp = buf[i]; 46 buf[i] = buf[lena - i]; 47 buf[lena - i] = tmp; 48 } 49 50 string res; 51 if(buf[0] > '0'){ 52 res = string(buf); 53 }else{ 54 res = string(buf + 1); 55 } 56 delete[] buf; 57 58 return res; 59 } 60 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)