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();
        }
    }
  • 相关阅读:
    maven搭建
    javascript
    FTP工具类
    jsp相关知识
    java mail 邮箱发送
    servlet相关
    hibernate文档
    6月
    Spring AOP 使用总结
    spring事务配置总结
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12591185.html
Copyright © 2011-2022 走看看