其他分享
首页 > 其他分享> > leetcode - 67 二进制求和

leetcode - 67 二进制求和

作者:互联网

  1. 首先将a字符串设置为较长的那一个
  2. 开辟两个Stringbuffer,较长的那一个数字头部多加一个0
  3. 另一个较短的前部补0到两者长度相同,方便计算
  4. 计算,进位,循环
  5. 设置最高位
class Solution {
    public String addBinary(String a, String b) {
        if(a.length() < b.length()){
            String temp = a;
            a = b;
            b = temp;
        }
        StringBuilder addOne = new StringBuilder("0");
        addOne.append(a);
        StringBuilder addTwo = new StringBuilder();
        int diff = addOne.length()-b.length();
        while(diff>=0){
            addTwo.append("0");
            diff--;
        }
        addTwo.append(b);
        int carryin = 0,sum = 0;
        for(int i = addOne.length()-1;i>0;i--){
            sum = (int)(addOne.charAt(i)-'0')+(int)(addTwo.charAt(i)-'0')+carryin;
            if(sum%2 == 1)
                addOne.setCharAt(i, '1');
            else
                addOne.setCharAt(i, '0');
            carryin = sum /2;
        }
        if(carryin == 0){
            addOne.deleteCharAt(0);
            return addOne.toString();
        }else{
            addOne.setCharAt(0, '1');
            return addOne.toString();
        }
    }
}

用到的Stringbuffer API总结:
StringBuffer:::deleteCharAt(int index)
StringBuffer:::setCharAt(int index,char chr)
StringBuffer:::CharAt(int index)
StringBuffer:::append(…) //在尾部增添字符串

标签:二进制,StringBuffer,addOne,addTwo,int,length,carryin,67,leetcode
来源: https://blog.csdn.net/qq_36323559/article/details/98206828