zoukankan      html  css  js  c++  java
  • 【leetcode】AddBinary

    解题思路:

    • 首先把字符串ab补齐到同样长度,前面补零
    • 然后对应位做加法器,设置一个进位位
    • 字符转换成数字需要 -'0'
    • 数字转换为字符需要 +'0'
    • 结果字符数组需要比ab多一位
    • 最前面的一位为最后的进位位
      • 判断最后的进位如果为1,则设置结果数组第一位为1,创建字符串用result数组全部
      • 如果为0,则设置结果字符数组第一位为0,创建字符串用1到最后
        • 注意
          • 10都需要转换为char,不然会乱码,因为是acssi
          • 创建字符1到最后,是1result.lenght-1

    代码:

    package leetcode;

       

    /**

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

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

    *

    */

    public class AddBinary {

        public static void main(String[] args) {

            String a = "101";

            String b = "1";

            int max_a_b = Math.max(a.length(), b.length());

            if (a.length() >= b.length()) {

                b = String.format("%0" + max_a_b + "d", Integer.parseInt(b));

            } else {

                a = String.format("%0" + max_a_b + "d", Integer.parseInt(a));

            }

       

            System.out.println("after zeroize string a is " + a + " "

                    + "after zeroize string b is " + b);

            char[] achar = a.toCharArray();

            char[] bchar = b.toCharArray();

       

            char[] result = new char[Math.max(achar.length, bchar.length) + 1];

            int k = result.length - 1;// k is to the start of result

            int i = max_a_b - 1;

       

            int carry = 0;// 进位

            int aint = 0;

            int bint = 0;

            while (i >= 0) {

                aint = achar[i] - '0';

                bint = bchar[i] - '0';

                if (aint + bint + carry > 1) {

                    result[k] = (char) ('0' + aint + bint + carry - 2);

                    carry = 1;

       

                } else {

                    result[k] = (char) ('0' + aint + bint + carry);

                    carry = 0;

       

                }

                k--;

                i--;

            }

            if (carry == 1) {

                result[k] = (char) ((char) carry + '0');

                System.out.println("result is " + new String(result));

            } else {

                result[k] = (char) ((char) carry + '0');

                System.out.println("result is "

                        + new String(result, 1, result.length - 1));

            }

        }

    }

       

  • 相关阅读:
    layoutSubviews总结
    Vue.js:循环语句
    Vue.js:条件与循环
    Vue.js:模版语法
    Vue.js:起步
    Vue.js-Runoob:目标结构
    Vue.js-Runoob:安装
    Runoob-Vue.js:教程
    Vue.js:template
    培训-Alypay-Cloud:蚂蚁金融云知识点
  • 原文地址:https://www.cnblogs.com/keedor/p/4366721.html
Copyright © 2011-2022 走看看