zoukankan      html  css  js  c++  java
  • leetcode : Add Bianry 基本功 字符转整数

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

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

    tag: 字符asc码 。字符和数字加减法 。 '1' - '0' = 1 .  '1' - 0 != 0

    public class Solution {
        public String addBinary(String a, String b) {
            StringBuilder result = new StringBuilder();
            if(a == null && b == null) {
                return result.toString();
            }
            if(a == null) {
                return b;
            }
            if(b == null) {
                return a;
            }
            int aIndex = a.length() - 1;
            int bIndex = b.length() - 1;
            int carry = 0;
            
            while(aIndex >= 0 && bIndex >= 0) {
                int sum = (int)((a.charAt(aIndex) - '0') + (b.charAt(bIndex) - '0') + carry ) % 2;
                carry = (int)((a.charAt(aIndex) - '0') + (b.charAt(bIndex) - '0') + carry ) / 2;
                result.append(sum);
                aIndex--;
                bIndex--;
            }
            
            while(aIndex >= 0){
                int sum = (int)((a.charAt(aIndex) - '0') + carry ) % 2;
                carry = (int)((a.charAt(aIndex) - '0') + carry) / 2;
                result.append(sum);
                aIndex--;
            }
            
             while(bIndex >= 0){
                int sum = (int)((b.charAt(bIndex) - '0') + carry ) % 2;
                carry = (int)((b.charAt(bIndex) - '0') + carry) / 2;
                result.append(sum);
                bIndex--;
            }
            
            if(carry == 1) {
                result.append("1");
            } 
            
            return result.reverse().toString();
            
            
        }
    }
    

      

  • 相关阅读:
    Mockito 简明教程
    说说初用 Mock 工具测试碰到的坑
    java的mock测试框架
    使用模拟对象(Mock Object)技术进行测试驱动开发
    微信小程序
    微信小程序
    uniapp
    微信小程序
    微信小程序
    微信小程序
  • 原文地址:https://www.cnblogs.com/superzhaochao/p/6480609.html
Copyright © 2011-2022 走看看