• 67. Add Binary


    给定两个二进制字符串,返回它们的和(也是一个二进制字符串)

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

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

    lx223的解法
    public class Solution {
        public String addBinary(String a, String b) {
            StringBuilder sb = new StringBuilder();
            int i = a.length() - 1, j = b.length() -1, carry = 0;
            while (i >= 0 || j >= 0) {//从后往前加,因为后面是低位,前面是高位
                int sum = carry;
                if (j >= 0) sum += b.charAt(j--) - '0';//(j--)返回j,再做--操作
                if (i >= 0) sum += a.charAt(i--) - '0';
                sb.append(sum % 2);
                carry = sum / 2;
            }
            if (carry != 0) sb.append(carry);
            return sb.reverse().toString();
        }
    }



    我的解法

    class Solution {
    public String addBinary(String a, String b) {
    if (a.isEmpty())
    return b;
    if (b.isEmpty())
    return a;

    int carry = 0;
    int addA = 0;
    int addB = 0;
    StringBuilder aB = new StringBuilder(a);
    StringBuilder bB = new StringBuilder(b);

    aB.reverse();
    bB.reverse();

    StringBuilder sum = new StringBuilder();

    for (int i = 0; i < Math.max(a.length(), b.length()); i++) {
    if (i >= a.length())
    addA = 0;
    else
    addA = aB.charAt(i) - '0';

    if (i >= b.length())
    addB = 0;
    else
    addB = bB.charAt(i) - '0';

    sum.insert(0, (addA + addB + carry) % 2);

    if (addA + addB + carry >= 2)
    carry = 1;
    else
    carry = 0;

    }
    if (carry == 1)
    sum.insert(0, 1);
    return sum.toString();
    }
    }

  • 相关阅读:
    pthread_key_t和pthread_key_create()详解
    oracle的时间
    spring加载bean报错:expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
    MyBatis调用存储过程
    java的时间
    java的日期
    java中的多态
    笔记本设置wifi热点并抓包
    WiresShark使用说明
    HTTP协议概述
  • 原文地址:https://www.cnblogs.com/mafang/p/8651514.html
Copyright © 2020-2023  润新知