ID | Title | Difficulty | |
---|---|---|---|
Loading... |
67. Add Binary
Easy
LeetCode
Math, String, Bit Manipulation, Simulation
Problem
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"
Code
class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int p1 = a.length() - 1;
int p2 = b.length() - 1;
int carry = 0;
while(p1 >= 0 || p2 >= 0){
int num1 = p1 >= 0 ? (a.charAt(p1) - '0') : 0;
int num2 = p2 >= 0 ? (b.charAt(p2) - '0') : 0;
int sum = num1 + num2 + carry;
sb.insert(0, sum % 2);
carry = sum / 2;
p1--;
p2--;
}
if(carry != 0){
sb.insert(0, carry);
}
return sb.toString();
}
}
按 <- 键看上一题!
66. Plus One
按 -> 键看下一题!
68. Text Justification