LeetCode Add Binary 結題報告,leetcode結題報告

來源:互聯網
上載者:User

LeetCode Add Binary 結題報告,leetcode結題報告

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".
解題報告:二進位加法,分類為:Easy。沒有任何演算法,就是按照普通的方法計算即可。
一開始寫了一個高低位reverse的,然後再從0到高位做加法,一直算到位元少的到頭,然後如果有進位(carry)再對剩餘的位元多的string做進位元運算。
後來發現不用reverse也可以,直接從最高位向0位計算。AC代碼如下:

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();    }}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.