LeetCode 67. Add Binary
原题链接在这里: https://leetcode.com/problems/add-binary/
题目:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
题解:
Have sum = current pointing value of a + current pointing value of b + carry.
If current point value is out of index bound, then use 0.
Time Complexity: O(max(a.length(), b.length())).
Space O(max(a.length(), b.length())).
AC Java:
1 class Solution { 2 public String addBinary(String a, String b) { 3 int len1 = a.length(); 4 int len2 = b.length(); 5 int i = len1-1; 6 int j = len2-1; 7 int carry = 0; 8 StringBuilder sb = new StringBuilder(); 9 while(i>=0 || j>=0 || carry >0){ 10 carry += i>=0 ? a.charAt(i)-'0' : 0; 11 carry += j>=0 ? b.charAt(j)-'0' : 0; 12 sb.insert(0, carry%2); 13 carry /= 2; 14 15 i--; 16 j--; 17 } 18 19 return sb.toString(); 20 } 21 }
类似Plus One, Add Strings.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】博客园2025新款「AI繁忙」系列T恤上架,前往周边小店选购
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步