LeetCode Add Binary Final Report and leetcode Final Report

Source: Internet
Author: User

LeetCode Add Binary Final Report and leetcode Final Report

Https://oj.leetcode.com/problems/add-binary/
Given two binary strings, return their sum (also a binary string ).
For example,
A = "11"
B = "1"
Return "100 ".
Solution Report: Binary addition, which is classified as Easy. There is no algorithm, that is, it can be calculated according to a common method.
At the beginning, I wrote a high/low reverse, and then added it from 0 to the high position, until the number of digits is less than the first, and then if there is a carry) perform carry operations on strings with multiple digits.
Later, it was found that reverse is not required, and the highest bit is directly calculated to the zero bit. The AC code is as follows:

public class Solution {    public String addBinary(String a, String b) {        StringBuffer result = new StringBuffer("");int i = a.length() - 1;int j = b.length() - 1;int carry = 0;int index = 0;int acurrent = 0;int bcurrent = 0;for(;i>=0||j>=0;i--,j--) {acurrent = i>=0? a.charAt(i) - '0' : 0;bcurrent = j>=0? b.charAt(j) - '0' : 0;int current = (acurrent + bcurrent + carry)%2;carry = (acurrent + bcurrent + carry)/2;result = result.insert(0, current);}if(carry ==1)  {  result.insert(0, '1');  }          return result.toString();    }}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.