zoukankan      html  css  js  c++  java
  • [LC] 67. Add Binary

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

    The input strings are both non-empty and contains only characters 1 or 0.

    Example 1:

    Input: a = "11", b = "1"
    Output: "100"

    Example 2:

    Input: a = "1010", b = "1011"
    Output: "10101"

    class Solution {
        public String addBinary(String a, String b) {
            int aIndex = a.length() - 1;
            int bIndex = b.length() - 1;
            int carry = 0;
            StringBuilder sb = new StringBuilder();
            while (aIndex >= 0 || bIndex >= 0) {
                int curIndex = carry;
                if (aIndex >= 0) {
                    curIndex += a.charAt(aIndex) - '0';            
                }
                if (bIndex >= 0) {
                    curIndex += b.charAt(bIndex) - '0';            
                }            
                sb.append(curIndex % 2);
                carry = curIndex / 2;
                aIndex -= 1;
                bIndex -= 1;
            }
            if (carry == 1) {
                sb.append(1);
            }
            return sb.reverse().toString();
        }
    }
  • 相关阅读:
    C 字符串
    C 函数指针、回调函数
    C 指针
    C 数组、枚举类型enum
    C 函数声明、函数参数
    C 内置函数
    C 流程控制
    C 储存类与运算符
    C变量和常量
    名词解释
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12591185.html
Copyright © 2011-2022 走看看