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 class Solution {
        /**The program is used to calculate the sum of two binaries. This is a fundamental problem.<br> 
         * @param a --binary string as the first operand
         * @param b --binary string as the second operand
         * @return a string --the sum of binary a and b
         * @author Averill Zheng
         * @version 2014-06-03
         * @since JDK 1.7
         */
        public String addBinary(String a, String b) {
            int lengthOfA = a.length(), lengthOfB = b.length();
    		StringBuffer resultBuffer = new StringBuffer();
    		int carry = 0;
    		while(lengthOfA > 0 && lengthOfB > 0){
    			int sum = (a.charAt(lengthOfA - 1) -'0') + (b.charAt(lengthOfB - 1)- '0') + carry;
    			carry = sum / 2;
    			resultBuffer.insert(0, sum % 2);
    			--lengthOfA;
    			--lengthOfB;
    		}
    		String remaining = (lengthOfA == 0)? b : a;
    		int index = (lengthOfA == 0) ? lengthOfB : lengthOfA;
    		while(index > 0){
    			int sum = (remaining.charAt(index - 1) -'0') + carry;
    			carry = sum / 2;
    			resultBuffer.insert(0, sum % 2);
    			--index;
    		}
    		if(carry != 0)
    			resultBuffer.insert(0, 1);
    		return resultBuffer.toString();        
        }
    }
    

      

  • 相关阅读:
    ie兼容问题整理
    jQuery Easing 使用方法及其图解
    前端模块化学习
    velocity常用语句速查表
    table插件实现
    表单自动提交问题整理
    移动端开发
    工具的使用及配置
    《TCP/IP详解 卷1:协议》读书笔记
    iOS 内存泄漏
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3769098.html
Copyright © 2011-2022 走看看