• [Leetcode] Add Binary


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

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

    Solution:

     1 public class Solution {
     2     public String addBinary(String a, String b) {
     3         if(a==null)
     4             return b;
     5         if(b==null)
     6             return a;
     7         int end_a=a.length()-1;
     8         int end_b=b.length()-1;
     9         int carry=0;
    10         String result="";
    11         while(end_a>=0&&end_b>=0){
    12             int temp=(a.charAt(end_a)-'0')+(b.charAt(end_b)-'0')+carry;
    13             carry=temp/2;
    14             temp%=2;
    15             result=(temp+"")+result;
    16             end_a--;
    17             end_b--;
    18         }
    19         while(end_a>=0){
    20             int temp=(a.charAt(end_a)-'0')+carry;
    21             carry=temp/2;
    22             temp%=2;
    23             result=(temp+"")+result;
    24             end_a--;
    25         }
    26         while(end_b>=0){
    27             int temp=(b.charAt(end_b)-'0')+carry;
    28             carry=temp/2;
    29             temp%=2;
    30             result=(temp+"")+result;
    31             end_b--;
    32         }
    33         if(carry!=0){
    34             result=(carry+"")+result;
    35         }
    36         return result;
    37     }
    38 }
  • 相关阅读:
    C语言I博客作业10
    C言I博客作业09
    C言I博客作业08
    C语言I博客作业07
    C语言I博客作业06
    C语言博客园作业05
    使用注解方式生成Hibernate映射文件
    技术英语单词中英文对照
    spring监听器
    Servlet
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4110962.html
Copyright © 2020-2023  润新知