js9905com金沙网站LeetCode:67. Add Binary,leetcodebinary

LeetCode:67. Add Binary,leetcodebinary

题目:

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

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

这道题目是一个字符串处理人位上进行运算,不清楚Python封闭好了,实现起来会不会比较麻烦。Java这里如果可以像C/C++ 直接进行二进制运算的话,也是一处思路。我刚开始一上手做起来确实是觉得不太会,其实就是自己去实现一个二进制加法,再配合模2,余2,掌握好进位的计算。再贴一个官方论坛里的解题代码。

Solution:

public String addBinary(String a, String b) {
     StringBuilder sb = new StringBuilder();

    int i = a.length() -1 ;
     int j = b.length() - 1;
     int sum,carry = 0;

    while (i >= 0 || j >= 0) {
         sum = carry;

        if ( i >= 0 ) sum += a.charAt(i--) - '0' ;
         if ( j >= 0 ) sum += b.charAt(j--) - '0' ;

        sb.append(sum % 2);

        carry = sum / 2;
     }

    if (carry != 0) sb.append(carry);

    return sb.reverse().toString();

}

. Add Binary,leetcodebinary 题目: Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100" . 这道题目是一个...

本文由js9905com金沙网站-金沙澳门手机版网址发布于计算机,转载请注明出处:js9905com金沙网站LeetCode:67. Add Binary,leetcodebinary

您可能还会对下面的文章感兴趣: