zoukankan      html  css  js  c++  java
  • [LeetCode]Add Binary

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

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

    题解:二进制字符串相加

    public String addBinary(String a, String b) {
    		 
    		   //c表示为进位的
    			int len1 = a.length()-1,len2 = b.length()-1,c=0;
    			StringBuffer sb	= new StringBuffer();
    			while(len1>=0 && len2>=0){
    				
    				int temp = (a.charAt(len1)-'0')+(b.charAt(len2)-'0')+c;
    				c = temp/2;
    				temp = temp%2;
    				sb.insert(0, temp+"");
    				len1--;
    				len2--;
    			}
    			while(len1>=0){
    				int temp = (a.charAt(len1)-'0')+c;
    				c = temp/2;
    				temp = temp%2;
    				sb.insert(0, temp+"");
    				len1--;
    			}
    			while(len2>=0){
    				int temp = (b.charAt(len2)-'0')+c;
    				c = temp/2;
    				temp = temp%2;
    				sb.insert(0, temp+"");
    				len2--;
    			}
    			//注意1,1的情况要进位
    			if(c==1)
    			    sb.insert(0,c+"");
    			return sb.toString();
    		 }
    

    别人的短码:

    public String addBinary(String a, String b) {
        StringBuilder sb = new StringBuilder();
        int carry = 0;
        for(int i=a.length()-1,j=b.length()-1;i>=0 || j>=0;i--,j--){
            int v1 = (i<0)?0:a.charAt(i)-'0';
            int v2 = (j<0)?0:b.charAt(j)-'0';
            int val = (v1+v2+carry)%2;
            carry = (v1+v2+carry)/2;
            sb.insert(0,(char)(val+'0'));
        }
        if(carry == 1) sb.insert(0,'1');
        return sb.toString();
    }
    

      

  • 相关阅读:
    算法之递归
    初读 c# IL中间语言
    sql语句转为Model
    WPF-悬浮窗(类似于360)
    call,apply
    作用域题目
    css BFC
    数组扁平化 flatten
    常见的异步题
    setTimeout、Promise、Async/Await 的区别
  • 原文地址:https://www.cnblogs.com/lzeffort/p/4833712.html
Copyright © 2011-2022 走看看