2014-05-02 09:54
原题:
You have two numbers decomposed in binary representation, write a function that sums them and returns the result. Input: 100011, 100100 Output: 1000111
题目:做二进制加法。
解法:字符串就行了,不需要额外开辟数组。string对象本身就是一个vector,也就是一个数组喽。
代码:
1 // http://www.careercup.com/question?id=4892713614835712 2 #include <iostream> 3 #include <string> 4 using namespace std; 5 6 string binaryAdd(string &a, string &b) 7 { 8 if (a.length() > b.length()) { 9 return binaryAdd(b, a); 10 } 11 12 string c; 13 int carry; 14 int na, nb; 15 int bita, bitb; 16 int i; 17 18 reverse(a.begin(), a.end()); 19 reverse(b.begin(), b.end()); 20 21 na = (int)a.length(); 22 nb = (int)b.length(); 23 carry = 0; 24 for (i = 0; i < nb; ++i) { 25 bita = i < na ? a[i] - '0' : 0; 26 bitb = b[i] - '0'; 27 c.push_back((bita ^ bitb ^ carry) + '0'); 28 carry = (bita + bitb + carry) > 1; 29 } 30 if (carry) { 31 c.push_back('1'); 32 } 33 reverse(c.begin(), c.end()); 34 35 return c; 36 } 37 38 int main() 39 { 40 string a, b, c; 41 42 while (cin >> a >> b) { 43 c = binaryAdd(a, b); 44 cout << c << endl; 45 } 46 47 return 0; 48 }
【推荐】国内首个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新功能体验(一)