一. 问题描述
给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 1 和 0。
示例 1:
输入: a = "11", b = "1"
输出: "100"
示例 2:
输入: a = "1010", b = "1011"
输出: "10101"
二. 解题思路
本题采用补齐字符串+按位字符串相加+对字符串进行二进制化的方法进行。
步骤一:将a,b两个不等长的字符串进行补齐,方便其按位进行运算。
步骤二:创建字符串c比等长的字符串长度多1。
步骤三:将a,b两个等长字符串进行按位运算,结果从c的最后一位开始放。
步骤四:从最后一位开始对c进行判断,如果大于1,向前进一位并将该位置减2。
步骤五:判断c第一位的值,如果是1则直接输出c,如果是0,则删除第一位输出c。
三. 执行结果
执行用时 :4 ms, 在所有 java 提交中击败了77.89%的用户
内存消耗 :36.2 MB, 在所有 java 提交中击败了55.12%的用户
四. Java代码
class Solution { public String addBinary(String a, String b) { int a_1=a.length(); int b_1=b.length(); if(a_1>b_1) for(int i=0;i<a_1-b_1;i++) { b="0"+b; } else { for(int i=0;i<b_1-a_1;i++) { a="0"+a; } } char []tempA=a.toCharArray(); char []tempB=b.toCharArray(); char []tempc=new char[Math.max(tempA.length, tempB.length)+1]; tempc[0]='0'; for(int i=tempA.length-1,c=tempc.length-1;i>=0&&c>=0;i--,c--) { tempc[c]=(char)((int)tempA[i]+(int)tempB[i]-(int)('0')); } for(int i=tempc.length-1;i>0;i--) { if(tempc[i]=='2') { tempc[i]='0'; tempc[i-1]=(char)((int)tempc[i-1]+1); } if(tempc[i]=='3') { tempc[i]='1'; tempc[i-1]=(char)((int)tempc[i-1]+1); } } String tempall=""; if(tempc[0]=='1') { String temp=new String(tempc); return temp; } else { for(int m=1;m<tempc.length;m++) { tempall=tempall+tempc[m]; } return tempall; } } }