zoukankan      html  css  js  c++  java
  • 67. Add Binary java solutions

    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         
     4         if(a.length() > b.length()){//将字符串长的作为b,方便后面字符串长的处理
     5             String tmp = b;
     6             b = a;
     7             a = tmp;
     8         }
     9         int alen = a.length()-1, blen = b.length()-1;
    10         String ans = "";
    11         int high = 0, tmp = 0;
    12         while(alen >= 0){
    13             tmp = (int)(a.charAt(alen--)-'0') + (int)(b.charAt(blen--)-'0') + high;// 需要做下int的强制类型转换,不然internal error
    14             ans = "" + tmp%2 + ans;
    15             high = tmp/2;
    16         }
    17         while(blen >= 0){
    18             tmp = (int)(b.charAt(blen--)-'0') + high;
    19             ans = "" + tmp%2 + ans;
    20             high = tmp/2;
    21         }
    22         if(high == 1) ans ="" + 1 + ans;
    23         return ans;
    24     }
    25 }
  • 相关阅读:
    angularjs $index用来取顺序
    angularjs &登录跳转
    if(!confirm("您确定删除吗?")){return;}
    登录跳转
    undefined null测试
    git生成密钥
    遍历map
    网络相关名词解释
    redis的Pub/Sub
    SQLAlchemy的使用
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5629975.html
Copyright © 2011-2022 走看看