Leet Code 67 Add Binary - 二进制加法 - Java
2016-06-24 00:00
465 查看
摘要: Leet Code 67 Add Binary - 二进制加法 - Java
问题原始链接 https://leetcode.com/problems/add-binary
给定两个二进制字符串,以二进制字符串形式返回它们的和。
例如:a = "11",b = "1",返回 "100"。
问题原始链接 https://leetcode.com/problems/add-binary
给定两个二进制字符串,以二进制字符串形式返回它们的和。
例如:a = "11",b = "1",返回 "100"。
public class Solution { public static String addBinary(String a, String b) { if (a == null || a.length() == 0) { return b; } if (b == null || b.length() == 0) { return a; } StringBuilder result = new StringBuilder( Math.max(a.length(), b.length()) + 1); int minLen = Math.min(a.length(), b.length()); int carry = addBinary(a, b, minLen, result); if (a.length() > minLen) { carry = addBinary(a, carry, a.length() - 1 - minLen, result); } else if (b.length() > minLen) { carry = addBinary(b, carry, b.length() - 1 - minLen, result); } if (carry > 0) { result.append(carry); } return result.reverse().toString(); } private static int addBinary(String a, String b, int len, StringBuilder result) { int carry = 0; for (int i = 0; i < len; i++) { int d1 = Character.getNumericValue(a.charAt(a.length() - 1 - i)); int d2 = Character.getNumericValue(b.charAt(b.length() - 1 - i)); int x = d1 + d2 + carry; int d = x % 2; carry = x / 2; result.append(d); } return carry; } private static int addBinary(String a, int carry, int start, StringBuilder result) { for (int i = start; i >= 0; i--) { int d1 = Character.getNumericValue(a.charAt(i)); int x = d1 + carry; int d = x % 2; carry = x / 2; result.append(d); } return carry; } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解