Leetcode刷题记——67. Add Binary(二进制数相加)

一、题目叙述:

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

Subscribe to see which companies asked this question.

二、解题思路:

Easy题,我很佩服我的解法,真的好。。。烂,一个简单题写成这样。。。

(1)先把两个字符串长度填成一样转换成字符数组

(2)将字符数组内容倒序相加放进结果字符串(我麻烦的分情况写了。。。)

三、源码:

import java.util.ArrayList;  
import java.util.Arrays;
import java.util.List;  
  
public class Solution  
{  
	public String addBinary(String a, String b) 
	{
		String tmp = "";
		if (a.length() >= b.length())
		{
			for (int i = 0; i < a.length() - b.length(); i++)
				tmp += "0";
			b = tmp + b;
		}
		else
		{
			for (int i = 0; i < b.length() - a.length(); i++)
				tmp += "0";
			a = tmp + a;
		}
        char[] aa = a.toCharArray();
        char[] bb = b.toCharArray();
        String res = "";
        
        int len = aa.length - 1;
       // int bl = bb.length - 1;
        int n = 0;
        while (len >= 0)
        {
        	if (aa[len] == '1' && bb[len] == '1' )
        	{	res = n + res; n = 1;}
        	else if (aa[len] == '0' && bb[len] == '0')
        	{   res = n + res; n = 0;}
        	else if (n == 1)
        	{   res = "0" + res; n = 1;}
        	else
        	{   res = "1" + res; n = 0;}
        	len--;
        	
        }
        if (n == 1) res = "1" + res;
        return res;
        
    }
    public static void main(String args[])      
    {      
              
    	String a = "";
    	String b = "";
      //  int[] digits = {0};      
        Solution solution = new Solution();      
      //  int[][] abc = {{2,5},{8,4}};  
      //  int[] b = {2,3,4};  
       // for(int i = 0; i < abc.length; i ++)      
        
          System.out.print(solution.addBinary(a, b));      
          
    }      
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值