zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 67 二进制求和

    67. 二进制求和

    给定两个二进制字符串,返回他们的和(用二进制表示)。

    输入为非空字符串且只包含数字 1 和 0。

    示例 1:

    输入: a = “11”, b = “1”
    输出: “100”
    示例 2:

    输入: a = “1010”, b = “1011”
    输出: “10101”

    class Solution {
        public String addBinary(String a, String b) {
            if(a == null || a.length() == 0) return b;
            if(b == null || b.length() == 0) return a;
    
            StringBuilder stb = new StringBuilder();
            int i = a.length() - 1;
            int j = b.length() - 1;
            
            int c = 0;  // 进位
            while(i >= 0 || j >= 0) {
                if(i >= 0) c += a.charAt(i --) - '0';
                if(j >= 0) c += b.charAt(j --) - '0';
                stb.append(c % 2);
                c >>= 1;
            }
            
            String res = stb.reverse().toString();
            return c > 0 ? '1' + res : res;
        }
    }
    
  • 相关阅读:
    python 时间 时间戳 转换
    jsp mysql
    multi struts config
    mysql start
    struts logic tag
    jsp setProperty
    jstl fn tag
    write jsp tag
    use Bean in JSP
    jsp mysql JavaBean
  • 原文地址:https://www.cnblogs.com/a1439775520/p/12946848.html
Copyright © 2011-2022 走看看