Loading

67. 二进制求和

67. 二进制求和

https://leetcode-cn.com/problems/add-binary/description/

package com.test;

/**
 * @Author stono
 * @Date 2018/8/24 下午4:53
 */
public class Lesson067 {
    public static void main(String[] args) {
        String a = "11";
        String b = "1";
        char[] chars = a.toCharArray();
        for (char aChar : chars) {
            System.out.println(aChar);
        }
        String s = addBinary(a, b);
        System.out.println(s);
    }

    public static String addBinary(String a, String b) {

        // 把字符串转化为数组
        char[] charsA = a.toCharArray();
        char[] charsB = b.toCharArray();
        int lengthA = a.length();
        int lengthB = b.length();
        // 获取一个最大值,然后加1,构建结果数组
        int max = lengthA > lengthB ? (lengthA + 1) : (lengthB + 1);
        int[] charsC = new int[max];
        int i = lengthA - 1;
        int j = lengthB - 1;
        int k = max - 1;
        int ck = 0;
        // 从最后一位开始取值,进行累加
        for (; i > -1 && j > -1; i--, j--, k--) {
            int ai = charsA[i] - '0';
            int bj = charsB[j] - '0';
            int res = ck + ai + bj;
            charsC[k] = (res % 2);
            ck = (res > 1 ? 1 : 0);

        }
        // 把B里面的剩余加进来,这里的隐含条件是A遍历结束了;
        for (; j > -1; j--, k--) {
            int bj = charsB[j] - '0';
            int res = ck + bj;
            charsC[k] = (res % 2);
            ck = (res > 1 ? 1 : 0);
        }
        // 把A里面的剩余加进来,这里隐含条件是B遍历结束了;
        for (; i > -1; i--, k--) {
            int ai = charsA[i] - '0';
            int res = ck + ai;
            charsC[k] = (res % 2);
            ck = (res > 1 ? 1 : 0);
        }
        // 把最后进位的元素加进来
        charsC[0] = ck;
        if (charsC[0] == 0) {
            i = 1;
        } else {
            i = 0;
        }
        StringBuilder builder = new StringBuilder();
        for (; i < charsC.length; i++) {
            builder.append(charsC[i]);
        }
        return builder.toString();
    }
}

char 转int   char-'0'

 

posted @ 2018-08-24 17:46  stono  阅读(142)  评论(0编辑  收藏  举报