• [leetcode] Add Binary


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

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

    https://oj.leetcode.com/problems/add-binary/

    思路:类似大数计算只是进位有区别,小心carry的处理。

    public 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;
    
            int m = a.length(), n = b.length();
            StringBuilder res = new StringBuilder();
            int i = m - 1, j = n - 1;
            int x, y, c = 0;
            while (i >= 0 || j >= 0) {
                x = (i >= 0) ? a.charAt(i) - '0' : 0;
                y = (j >= 0) ? b.charAt(j) - '0' : 0;
                res.append(x ^ y ^ c);
                c = (x + y + c >= 2) ? 1 : 0;
                i--;
                j--;
            }
            if (c == 1)
                res.append(1);
    
            return res.reverse().toString();
    
        }
    
        public static void main(String[] args) {
            System.out.println(new Solution().addBinary("11", "1"));
            System.out.println(new Solution().addBinary("1111", "1111"));
            System.out.println(new Solution().addBinary("11", ""));
            System.out.println(new Solution().addBinary("11111111111111111111", "1"));
            System.out.println(new Solution().addBinary("0101", "1010"));
    
        }
    }
    View Code

     第二遍记录:

      注意是2进制加法。

      注意倒序取数据最后翻转。

      注意用位操作简化进位。

  • 相关阅读:
    python 时间等待
    python threading多线程
    c 字符串的结束标志
    c 输出是自动显示输出类型
    c 的占位符
    c数据类型
    游戏引擎
    java 数据类型
    python 读写json数据
    python 多线程_thread
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3812561.html
Copyright © 2020-2023  润新知