题解 | #二进制求和#

二进制求和

http://www.nowcoder.com/practice/1620262056c24c0e96de32fb261703d0

将字符串转换成倒转的数组,然后一次求和进制求解!

public class Solution {

public String binaryAdd (String A, String B) {
    // write code here
    StringBuilder stringBuilder = new StringBuilder();
    int carry = 0;
    int aLength = A.length();
    int bLength = B.length();
    int[] aChar = new int[aLength];
    int[] bChar = new int[bLength];
    for (int i = 0; i < aLength; i++) {
        aChar[i]=A.charAt(aLength-i-1)-48;
    }
    for (int i = 0; i < bLength; i++) {
        bChar[i]=B.charAt(bLength-i-1)-48;
    }
    int i=0;
    for(;i<aLength&&i<bLength;i++){
        stringBuilder.append((aChar[i]+bChar[i]+carry)%2);
        carry= (aChar[i]+bChar[i]+carry)/2;
    }
    while (i<aLength){
        stringBuilder.append((aChar[i]+carry)%2);
        carry= (aChar[i]+carry)/2;
        i++;
    }
    while (i<bLength){
        stringBuilder.append((bChar[i]+carry)%2);
        carry= (bChar[i]+carry)/2;
        i++;
    }
    if(carry==1){
        stringBuilder.append(1);
    }
    return stringBuilder.reverse().toString();
}

}

全部评论

相关推荐

LemontreeN:有的兄弟有的我今天一天面了五场,4个二面一个hr面
投递字节跳动等公司7个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务