zoukankan      html  css  js  c++  java
  • 二进制求和 —— 从复杂方法到简单方法

    给定两个二进制字符串,返回他们的和(用二进制表示)。

    输入为非空字符串且只包含数字 1 和 0。

    示例 1:
    输入: a = "11", b = "1"
    输出: "100"

    示例 2:
    输入: a = "1010", b = "1011"
    输出: "10101"

    我的思路

      一:我最开始的思路现在想想很傻很天真~,

        就是按部就班的把短的那一串字符串用0填充后,挨个进行加,然后标记一下他有没有进位。

      二:后来思路更加清晰,发现我之前的想法太......呆了哈哈哈哈~

    第一次代码:

        public static String addBinary(String a, String b) {
            String result = "";
            int alen = a.length();
            int blen = b.length();
            int len = 0;
         // 填充 0
    if (alen > blen) { int x = alen-blen; while (x > 0) { b = "0".concat(b); x--; } len = alen; } else { int x = blen-alen; while (x > 0) { a = "0".concat(a); x--; } len = blen; } //System.out.println(a + " "+ b); int sum = 0; int flag = 0; for (int i = len-1; i >= 0; i--) { sum = a.charAt(i) + b.charAt(i); //System.out.println(a.charAt(i)+" "+b.charAt(i));
           // '1'+'1' if (sum == 98) {
              // flag=1 上一步进位了 flag=0 上一步没进位
    if (flag == 1) { result = "1".concat(result); } else { result = "0".concat(result); } flag = 1;
           // '0'+'0' }
    else if (sum == 96) { if (flag == 1) { result = "1".concat(result); } else { result = "0".concat(result); } flag = 0;
           // '0'+'1' }
    else { if (flag == 1) { result = "0".concat(result); flag = 1; } else { result = "1".concat(result); flag = 0; } } } if (flag == 1) { result = "1".concat(result); } return result; }

    第二次代码:

        public static String addBinary(String a, String b) {
            StringBuffer result = new StringBuffer();
            int alen = a.length();
            int blen = b.length();
            int sum = 0;
            for (int i = alen - 1, j = blen - 1; i >= 0 || j >= 0; i--,j--) {
                if (i >= 0) {
                    sum += a.charAt(i) - '0';
                }
                if (j >= 0) {
                    sum += b.charAt(j) - '0';
                }
                // 求余后,算进位。比如sum=3,则这一位为3%2=1,进位3/2=1
                result.append(sum % 2);
                sum = sum / 2;
            }
            if (sum > 0) {
                result.append(1);
            }
         // 需要反转string哟~
    return result.reverse().toString(); }
  • 相关阅读:
    shell脚本,通过传入的参数来计算最大值和最小值以及平均值。
    mac date命令
    jstorm系列-2:入门
    jstorm系列-1:入门
    git 如何恢复只是提交到本地的文件(或者commit)
    shell 参数
    shell 运算符
    shell 中的<,<<,>,>>
    shell 学习笔记
    java 多线程剖析
  • 原文地址:https://www.cnblogs.com/BulingBuling/p/11423984.html
Copyright © 2011-2022 走看看