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

    题目地址:https://leetcode.com/problems/add-binary/description/

    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 i = a.length() - 1, j = b.length() - 1;
            Stack<String> stack = new Stack<String>();
            int jin = 0, num_a, num_b;
            while (i >= 0 && j >= 0){
                num_a = a.charAt(i--) == '0' ? 0 : 1;
                num_b = b.charAt(j--) == '0' ? 0 : 1;
                int temp = num_a + num_b + jin;
                stack.push(temp % 2 == 0 ? "0" : "1");
                jin = temp >> 1;
            }
            while (i >= 0) {
                num_a = a.charAt(i--) == '0' ? 0 : 1;
                int temp;
                if (jin != 0) {
                    temp = num_a + jin;
                } else {
                    temp = num_a;
                }
                stack.push(temp % 2 == 0 ? "0" : "1");
                jin = temp >> 1;
            } 
            while (j >= 0) {
                num_b = b.charAt(j--) == '0' ? 0 : 1;
                int temp;
                if (jin != 0) {
                    temp = num_b + jin;
                } else {
                    temp = num_b;
                }
                stack.push(temp % 2 == 0 ? "0" : "1");
                jin = temp >> 1;
            }
            if (jin != 0) {
                stack.push("1");
            }
            StringBuilder str = new StringBuilder();
            while (!stack.isEmpty()) {
                str.append(stack.pop());
            }
            return str.toString();
        }
    }

    写了半天发现评论区的一位大佬直接用BigInteger解决了,感觉智商被碾压。。。,贴上代码

    import java.math.*;
    class Solution {
        public String addBinary(String a, String b) {
            return (new BigInteger(a, 2).add(new BigInteger(b, 2))).toString(2);
        }
    }

    ========================================Talk is cheap, show me the code=======================================

    CSDN博客地址:https://blog.csdn.net/qq_34115899
  • 相关阅读:
    刚体动力学
    碰撞检测系统
    动画系统II
    动画系统
    Game Develop Books
    光照技术
    LR参数组取值操作方法
    loadrunner测试ajax框架
    ​Web(click and script) 与 Web(HTTP/HTML)协议区别
    性能测试常用的linux命令
  • 原文地址:https://www.cnblogs.com/lcy0515/p/9179756.html
Copyright © 2011-2022 走看看