LintCode 题目解答之字符串操作(1)
来源:互联网 发布:node.js高级编程 pdf 编辑:程序博客网 时间:2024/06/08 01:04
开头的一些话······这是我的第一篇博客,短短的一篇却写了1个多小时,很多东西都是在第一次摸索。前几天考了华为的线上笔试,虽然只有3题,但是第一题就花了我半个多小时,后面两题就更不用讲了。痛定思痛,还是因为自己几乎都没怎么练过这种东西。9月份初开始还有几场笔试,现在开始每天练至少2题,到时候也能练上十几题。我知道网上已经有数不清的类似的博客,但是别人想出来的解答终究不是自己的。在此把自己想出来的答案写成博客记录下来,虽是亡羊补牢,但还是能找找做这种题目的感觉,至于笔试能不能过,心里期望能胜天半子一下。
题目1:二进制求和(LintCode题号:408)
给定两个二进制字符串,返回他们的和(用二进制表示)。样例 a = 11 b = 1 返回 100
解答如下:
class Solution {public: /** * @param a: a number * @param b: a number * @return: the result */ string addBinary(string a, string b) { // write your code here bool bHasCarry = false; string strOut; int dwStrALen = a.size(); int dwStrBLen = b.size(); int dwOutIndex; if (dwStrALen >= dwStrBLen) { strOut = a; dwOutIndex = dwStrALen - 1; } else { strOut = b; dwOutIndex = dwStrBLen - 1; } int iA = dwStrALen - 1; int iB = dwStrBLen - 1; for (; (iA >= 0) && (iB >= 0); iA--, iB--, dwOutIndex--) // assume iA > iB { if (true == bHasCarry) { if (('1' == a[iA]) && ('1' == b[iB])) { bHasCarry = true; strOut[dwOutIndex] = '1'; } else if (('0' == a[iA]) && ('0' == b[iB])) { bHasCarry = false; strOut[dwOutIndex] = '1'; } else { bHasCarry = true; strOut[dwOutIndex] = '0'; } } else if (false == bHasCarry) { if (('1' == a[iA]) && ('1' == b[iB])) { bHasCarry = true; strOut[dwOutIndex] = '0'; } else if (('0' == a[iA]) && ('0' == b[iB])) { bHasCarry = false; strOut[dwOutIndex] = '0'; } else { bHasCarry = false; strOut[dwOutIndex] = '1'; } } } // now iB = -1 and iA == dwOutIndex while (0 <= dwOutIndex) { if (true == bHasCarry) { if ('0' == strOut[dwOutIndex]) { bHasCarry = false; strOut[dwOutIndex] = '1'; } else if ('1' == strOut[dwOutIndex]) { bHasCarry = true; strOut[dwOutIndex] = '0'; } } else if (false == bHasCarry) { if ('0' == strOut[dwOutIndex]) { bHasCarry = false; strOut[dwOutIndex] = '0'; } else if ('1' == strOut[dwOutIndex]) { bHasCarry = false; strOut[dwOutIndex] = '1'; } } dwOutIndex--; } // if overflow if ((0 > dwOutIndex) && (true == bHasCarry)) { strOut.insert(0, "1"); } return strOut; }};
阅读全文
0 0
- LintCode 题目解答之字符串操作(1)
- LintCode题目解答之字符串操作(2)
- LintCode 题目之Aplusb2
- C语言学习之文件操作(含重庆大学研究生程序设计大赛的题目和解答)
- 浙大复试上机题目解答(1)
- leetcode题目解答报告(1)
- LintCode之比较字符串
- LintCode之字符串置换
- LintCode之旋转字符串
- 面试题目及解答1
- SeedCoder2014热身题目1 -- 解答
- csdn题目(含解答)
- LintCode之8 旋转字符串
- LintCode之13 字符串查找
- 翻转字符串(LintCode)
- 面试题(一)-------面试中常见的字符串类型题目及思路解答
- 浙江大学计算机系硕士研究生复试题目解答(1)
- 题目解答
- link和@import的区别
- iOS开发 用UICollectionView仿网易新闻的滚动按钮效果
- 百度语音识别和合成
- 状态压缩DP总结【POJ3254】【POJ1185】【POJ3311】【HDU3001】【POJ2288】【ZOJ4257】【POJ2411】【HDU3681】
- python中的OS模块
- LintCode 题目解答之字符串操作(1)
- 成功的背后!(给所有IT人)
- 字典树模板
- ROS中使用USB摄像头
- win10快捷键冲突
- 组建AR、VR和MR的硬件共享实验室,你认为可能吗?
- HDU6058 Kanade's sum(链表)
- win10 windows文件夹就占用40G
- 前端,前端轮播的做法