Add Binary (Java)

来源:互联网 发布:2017广联达软件购买 编辑:程序博客网 时间:2024/06/07 04:08

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

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


Source

public class Solution {    public String addBinary(String a, String b) {        String c = new String();        int lena = a.length() - 1;   //直接置长度减1 不易越界        int lenb = b.length() - 1;        int carry = 0;                while(lena >= 0 || lenb >= 0){   //放在一起判断 不用把长的拿出来单独写(还得判断谁长加谁) 短的前面补0        int numa = (lena < 0 ? 0 : a.charAt(lena) - '0');        int numb = (lenb < 0 ? 0 : b.charAt(lenb) - '0');        int temp = (numa + numb + carry) % 2;        carry = (numa + numb + carry) / 2;        c = Integer.toString(temp) + c;        lena --;        lenb --;        }        if(carry == 1) c = '1' + c;   //最后一位有进位的情况        return c;    }}

Test

    public static void main(String[] args){    String a = "101010";    String b = "110101";    System.out.println(new Solution().addBinary(a, b));    }


0 0
原创粉丝点击