67:二进制求和
This commit is contained in:
parent
8bbbab2f81
commit
78c0539b96
56
src/main/java/leetcode/editor/cn/AddBinary.java
Normal file
56
src/main/java/leetcode/editor/cn/AddBinary.java
Normal file
@ -0,0 +1,56 @@
|
||||
//给你两个二进制字符串,返回它们的和(用二进制表示)。
|
||||
//
|
||||
// 输入为 非空 字符串且只包含数字 1 和 0。
|
||||
//
|
||||
//
|
||||
//
|
||||
// 示例 1:
|
||||
//
|
||||
// 输入: a = "11", b = "1"
|
||||
//输出: "100"
|
||||
//
|
||||
// 示例 2:
|
||||
//
|
||||
// 输入: a = "1010", b = "1011"
|
||||
//输出: "10101"
|
||||
//
|
||||
//
|
||||
//
|
||||
// 提示:
|
||||
//
|
||||
//
|
||||
// 每个字符串仅由字符 '0' 或 '1' 组成。
|
||||
// 1 <= a.length, b.length <= 10^4
|
||||
// 字符串如果不是 "0" ,就都不含前导零。
|
||||
//
|
||||
// Related Topics 位运算 数学 字符串 模拟 👍 762 👎 0
|
||||
|
||||
package leetcode.editor.cn;
|
||||
|
||||
//67:二进制求和
|
||||
public class AddBinary {
|
||||
public static void main(String[] args) {
|
||||
Solution solution = new AddBinary().new Solution();
|
||||
|
||||
}
|
||||
|
||||
//leetcode submit region begin(Prohibit modification and deletion)
|
||||
class Solution {
|
||||
public String addBinary(String a, String b) {
|
||||
StringBuilder str = new StringBuilder();
|
||||
int sum = 0;
|
||||
for (int i = a.length() - 1, j = b.length() - 1; i >= 0 || j >= 0; i--, j--) {
|
||||
sum += i >= 0 ? a.charAt(i) - '0' : 0;
|
||||
sum += j >= 0 ? b.charAt(j) - '0' : 0;
|
||||
str.insert(0, sum % 2);
|
||||
sum /= 2;
|
||||
}
|
||||
if (sum == 1) {
|
||||
str.insert(0, 1);
|
||||
}
|
||||
return str.toString();
|
||||
}
|
||||
}
|
||||
//leetcode submit region end(Prohibit modification and deletion)
|
||||
|
||||
}
|
26
src/main/java/leetcode/editor/cn/doc/content/AddBinary.md
Normal file
26
src/main/java/leetcode/editor/cn/doc/content/AddBinary.md
Normal file
@ -0,0 +1,26 @@
|
||||
<p>给你两个二进制字符串,返回它们的和(用二进制表示)。</p>
|
||||
|
||||
<p>输入为 <strong>非空 </strong>字符串且只包含数字 <code>1</code> 和 <code>0</code>。</p>
|
||||
|
||||
<p> </p>
|
||||
|
||||
<p><strong>示例 1:</strong></p>
|
||||
|
||||
<pre><strong>输入:</strong> a = "11", b = "1"
|
||||
<strong>输出:</strong> "100"</pre>
|
||||
|
||||
<p><strong>示例 2:</strong></p>
|
||||
|
||||
<pre><strong>输入:</strong> a = "1010", b = "1011"
|
||||
<strong>输出:</strong> "10101"</pre>
|
||||
|
||||
<p> </p>
|
||||
|
||||
<p><strong>提示:</strong></p>
|
||||
|
||||
<ul>
|
||||
<li>每个字符串仅由字符 <code>'0'</code> 或 <code>'1'</code> 组成。</li>
|
||||
<li><code>1 <= a.length, b.length <= 10^4</code></li>
|
||||
<li>字符串如果不是 <code>"0"</code> ,就都不含前导零。</li>
|
||||
</ul>
|
||||
<div><div>Related Topics</div><div><li>位运算</li><li>数学</li><li>字符串</li><li>模拟</li></div></div><br><div><li>👍 762</li><li>👎 0</li></div>
|
Loading…
Reference in New Issue
Block a user