LeetCode(56)-Add Binary
2016-11-09 00:00
302 查看
题目:
Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100".
思路:
题意:对字符串的二进制数字,计算把二进制转化为整数,设置变量carry位进位,sum%2,是相应的数字,carry = sum/2
-
代码:
public class Solution { public String addBinary(String a, String b) { if(a.length() < b.length()){ String tmp = a; a = b; b = tmp; } int lengthA = a.length()-1; int lengthB = b.length()-1; int carry = 0; String all = ""; while(lengthB >= 0){ int num = (int)(a.charAt(lengthA)-'0')+(int)(b.charAt(lengthB)-'0')+carry; int k = num%2; carry = num/2; all = String.valueOf(k)+all; lengthA--; lengthB--; } while(lengthA >= 0){ int num = (int)(a.charAt(lengthA)-'0')+carry; int k = num%2; carry = num/2; all = String.valueOf(k)+all; lengthA--; } if(carry == 1){ all = "1"+all; } return all; } }
相关文章推荐
- LeetCode(56)-Add Binary
- LeetCode(56)-Add Binary
- LeetCode(56)-Add Binary
- LeetCode 67. Add Binary
- LeetCode:Add Binary
- 56 leetcode - Jump Game
- [leetcode]Add Binary
- leetcode第一刷_Add Binary
- [leetcode刷题系列]Add Binary
- Add Binary —LeetCode
- Add Binary - LeetCode
- 【leetcode刷题笔记】Add Binary
- LeetCode---Add Binary
- leetcode -- 67. Add Binary【统一形式简化代码+双指针 + 二进制规则 + 字符数字转换】
- LeetCode Weekly Contest 56 Find K-th Smallest Pair Distance
- LeetCode 56, Merge Intervals 从 TLE 到 AC
- 【LeetCode】-Add Binary
- [LeetCode]Add Binary
- leetcode | Add Binary
- Leetcode 67. Add Binary