美文网首页
leetcode第67题二进制求和

leetcode第67题二进制求和

作者: CoderAPang | 来源:发表于2018-06-11 17:00 被阅读0次
class Solution {
    public String addBinary(String a, String b) {
        int length_a = a.length();
        int length_b = b.length();
        String newBinary = "";
        int flag = 0;
        int num = 0;
        while(length_a>0&&length_b>0){
           num=(int)a.charAt(length_a-1)-'0'+(int)b.charAt(length_b-1)-'0'+flag;
            newBinary=num%2+newBinary;
            if(num>=2)flag = 1;
            else flag = 0;
            num =0;
            length_a--;
            length_b--;
        }
        while(length_a>0){
             num=(int)a.charAt(length_a-1)-'0'+flag;
            newBinary=num%2+newBinary;
            if(num>=2)flag = 1;
            else flag = 0;
            num =0;
            length_a--;
        }
        while(length_b>0){
            num=(int)b.charAt(length_b-1)-'0'+flag;
            newBinary=num%2+newBinary;
            if(num>=2)flag = 1;
            else flag = 0;
            num =0;
            length_b--;
        }
        if(flag==1)newBinary="1"+newBinary;
        return newBinary;
    }
}

相关文章

网友评论

      本文标题:leetcode第67题二进制求和

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