Leetcode 67.Add Binary

作者: 沉默的叔叔 | 来源:发表于2016-12-04 23:05 被阅读51次

    题目


    Add Binary

    题目大意:给定两个二进制数的字符串字符串,返回它们的和的二进制字符串。

    开始的思路是将二进制转换成十进制相加,再把和转换成二进制,结果输入为

    "10100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101"

    "110101001011101110001111100110001010100001101011101010000011011011001011101111001100000011011110011"

    很自然地就溢出了,最后只能手动模拟相加过程。

    代码如下

    public class Solution {
        public String addBinary(String a, String b) {
            String restr = "";//储存相加的结果(倒序)
            int length = a.length()>b.length()?a.length():b.length();//较长字符串长度
            //在较短字符串前加0,使两个字符串一样长
            String chang = "";
            for (int i = 0;i<(a.length()>b.length()?a.length():b.length())-(a.length()<b.length()?a.length():b.length());i++)
                chang = chang + 0;
            if (a.length()>b.length()){
                chang = chang + b;
                b = chang;
            }
            else {
                chang = chang + a;
                a = chang;
            }
            int adc = 0;//储存进位
            //手动模拟相加
            for (int i=0;i<length;i++){
                if(a.charAt(length-i-1) + b.charAt(length-i-1) + adc - 2 * '0' == 3){
                    adc = 1;
                    restr = restr + 1;
                }
                else if (a.charAt(length-i-1) + b.charAt(length-i-1) + adc - 2 * '0' == 2){
                    adc = 1;
                    restr = restr + 0;
                }
                else if (a.charAt(length-i-1) + b.charAt(length-i-1) + adc - 2 * '0' == 1){
                    adc = 0;
                    restr = restr + 1;
                }
                else if (a.charAt(length-i-1) + b.charAt(length-i-1) + adc - 2 * '0' == 0){
                    adc = 0;
                    restr = restr + 0;
                }
            }
            //当进位为1说明结果还要加1
            if (adc == 1)
                restr = restr + 1;
            //将倒序的结果顺序变为正向
            String str = "";
            for (int i=0;i<restr.length();i++)
                str = str + restr.charAt(restr.length()-i-1);
            return str;
        }
    }
    

    相关文章

      网友评论

        本文标题:Leetcode 67.Add Binary

        本文链接:https://www.haomeiwen.com/subject/qdrhmttx.html