zoukankan      html  css  js  c++  java
  • Add Binary

    Add Binary

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

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

     1 public class Solution {
     2     public String addBinary(String a, String b) {
     3         char num1[] = a.toCharArray();
     4         char num2[] = b.toCharArray();
     5         int result[] = new int[Math.max(a.length(), b.length()) + 1];//保存结果
     6         int i = num1.length - 1;
     7         int j = num2.length - 1;
     8         int k = result.length - 1;
     9         while(i >= 0 && j >= 0){
    10             if(num1[i] == '1' && num2[j] == '1')
    11                 result[k--] = 2;
    12             else if(num1[i] == '0' && num2[j] == '0')
    13                 result[k--] = 0;
    14             else
    15                 result[k--] = 1;
    16             i--;
    17             j--;
    18         }//至少有一个计算完成
    19         while(i >= 0){
    20             result[k--] = num1[i--] - '0';
    21         }
    22         while(j >= 0)
    23             result[k--] = num2[j--] - '0';
    24         k = result.length - 1;
    25         while(k > 0){
    26             if(result[k] / 2 == 1)
    27             {
    28                 result[k - 1] += 1;
    29                 result[k] %= 2;
    30             }
    31             k--;
    32         }
    33         String ret = "";
    34         if(result[0] != 0){
    35             for(i = 0; i < result.length; i++)
    36                 ret += String .valueOf(result[i]);
    37         }
    38         else
    39         {
    40             for(i = 1; i < result.length; i++)
    41                 ret += String .valueOf(result[i]);
    42         }
    43         return ret;
    44     }
    45 }
  • 相关阅读:
    hdu4549 M斐波那契数列(矩阵快速幂+费马小定理)
    E. 因数串(EOJ Monthly 2020.7 Sponsored by TuSimple)
    2019春总结作业
    大一下半年学期总结
    ball小游戏
    贪吃蛇
    链接远程仓库
    git自动上传脚本及基本代码
    模板 --游戏
    飞机小游戏
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4088284.html
Copyright © 2011-2022 走看看