sequence

This article mainly records the binary sum of Leetcode

The title

Given two binary strings, return their sum (in binary). The input is a non-empty string containing only the digits 1 and 0. Example 1: Input: A = "11", b = "1" Output: "100" Example 2: Input: A = "1010", b = "1011" Output: "10101" Tip: Each string consists of only the character '0' or '1'. 1 <= a.length, b.length <= 10^4 Strings that are not "0" do not contain leading zeros. Source: LeetCode Link: https://leetcode-cn.com/problems/add-binary Copyright belongs to The Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.Copy the code

Answer key

class Solution { public String addBinary(String a, String b) { StringBuilder builder = new StringBuilder(); int i = a.length() - 1; int j = b.length() - 1; int sum = 0; while(i >= 0 || j >= 0) { if(i >= 0) { sum += a.charAt(i) - '0'; i--; } if(j >= 0) { sum += b.charAt(j) - '0'; j--; } builder.append(sum % 2); sum = sum/2; } String result = builder.reverse().toString(); return sum > 0 ? '1' + result : result; }}Copy the code

summary

Then modulo 2, continue the loop, and finally reverse the result. Finally, determine if sum is greater than 0. If sum is greater than 0, add prefix 1.

doc

  • Binary sum