二进制求和,lintcode
2016-12-11 14:04
423 查看
给定两个二进制字符串,返回他们的和(用二进制表示)。
样例
a = 11
b = 1
返回 100
解题思路:和十进制的求和没什么区别。注意细节就好了。下面的代码可以ac,但是冗余,可以优化为第二种方法。
一刷ac
样例
a = 11
b = 1
返回 100
解题思路:和十进制的求和没什么区别。注意细节就好了。下面的代码可以ac,但是冗余,可以优化为第二种方法。
一刷ac
public class Solution { /** * @param a a number * @param b a number * @return the result */ public String addBinary(String a, String b) { if(a.length() == 0 && b.length() == 0) return ""; int carry = 0; int i = a.length()-1; int j = b.length()-1; String res = ""; while(i >= 0 && j >= 0){ int value = carry + (a.charAt(i)-'0') + (b.charAt(j)-'0'); carry = value / 2; value = value % 2; res = String.valueOf(value) + res; i--; j--; } while(i >= 0){ int value = carry + a.charAt(i) - '0'; carry = value / 2; value = value % 2; res = String.valueOf(value) + res; i--; } while(j >= 0){ int value = carry + b.charAt(j) - '0'; carry = value / 2; value = value % 2; res = String.valueOf(value) + res; j--; } if(carry > 0) res = String.valueOf(carry) + res; return res; } }
public class Solution { /** * @param a a number * @param b a number * @return the result */ public String addBinary(String a, String b) { if(a.length() == 0 && b.length() == 0) return ""; int i = a.length() - 1; int j = b.length() - 1; String res = ""; int carry = 0; while(i >= 0 || j >= 0){ int sum = carry; if(i >= 0) sum += a.charAt(i) - '0'; if(j >= 0) sum += b.charAt(j) - '0'; res = String.valueOf(sum % 2) + res; carry = sum / 2; i--; j--; } if(carry > 0) res = String.valueOf(carry) + res; return res; } }
相关文章推荐
- Lintcode 408 二进制求和
- LIntCode-二进制求和
- 【LintCode-408】二进制求和(Java实现)
- lintCode(408)——二进制求和
- LintCode 二进制求和
- lintcode ----二进制求和
- LintCode(容易)二进制求和遇到的bug
- lintcode 二进制求和 给定两个二进制字符串,返回他们的和(用二进制表示)。
- LintCode | 408. 二进制求和
- lintcode --二进制求和
- 二进制求和(LintCode)
- LintCode之408 二进制求和
- LintCode【容易】二进制求和
- 二进制求和-LintCode
- 二进制表示-LintCode
- 连续子数组求和-LintCode
- 链表求和(LintCode)
- LintCode-剑指Offer-(376)二叉树路径求和
- 链表求和-LintCode
- lintcode ----链表求和