美文网首页ACM题库~
LeetCode 67. Add Binary

LeetCode 67. Add Binary

作者: 关玮琳linSir | 来源:发表于2017-09-26 20:36 被阅读19次

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

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

    题意:二进制加法,最后返回字符串,水题,直接上代码

    public String addBinary(String a, String b) {
                StringBuilder result = new StringBuilder();
            char[] as = a.toCharArray();
            char[] bs = b.toCharArray();
            int flag = 0;
    
            int i = as.length - 1, j = bs.length - 1;
    
            while (i >= 0 && j >= 0) {
                int c = as[i] + bs[j];
                switch (c) {
    
                case 96:
                    if (flag == 0) {
                        result.append(0);
                    } else {
                        result.append(1);
                    }
                    flag = 0;
                    break;
    
                case 97:
                    if (flag == 0) {
                        result.append(1);
                        flag = 0;
                    } else {
                        result.append(0);
                        flag = 1;
                    }
    
                    break;
    
                case 98:
                    if (flag == 0) {
                        result.append(0);
                        flag = 1;
                    } else {
                        result.append(1);
                        flag = 1;
                    }
    
                    break;
                }
                i--;
                j--;
    
            }
            if (i == -1) {
                while (j >= 0) {
                    if (flag == 1) {
                        if (bs[j] == '0') {
                            result.append('1');
                            flag = 0;
                        } else {
                            result.append(0);
                            flag = 1;
                        }
                    } else {
                        result.append(bs[j]);
                    }
                    j--;
                }
            }
    
            if (j == -1) {
                while (i >= 0) {
                    if (flag == 1) {
                        if (as[i] == '0') {
                            result.append('1');
                            flag = 0;
                        } else {
                            result.append(0);
                            flag = 1;
                        }
                    } else {
                        result.append(as[i]);
                    }
                    i--;
                }
            }
            if (flag == 1) {
                result.append('1');
            }
    
            return result.reverse().toString();
        }
    }
    

    相关文章

      网友评论

        本文标题:LeetCode 67. Add Binary

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