zoukankan      html  css  js  c++  java
  • LeetCode(67) Add Binary

    题目

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

    For example,
    a = “11”
    b = “1”
    Return “100”.

    分析

    一个简单的字符串相加,该题目要注意两点:

    1. 字符位的求和计算,必须转换为整型,即:
      如下利用‘0’字符作为中间转换,才得到正确结果。

      int temp = (a[i]-'0') + (b[i]-'0');
      
      char c = temp + '0';
    2. 进位保存于计算

    AC代码

    class Solution {
    public:
        string addBinary(string a, string b) {
            //首先,求得两个字符串的长度
            int la = strlen(a.c_str());
            int lb = strlen(b.c_str());
    
            //若其中一个字符串为空,直接返回另一个字符串即可
            if (la == 0)
                return b;
            else if (lb == 0)
                return a;
    
            //保存进位
            int carry = 0 ;
            //保存结果
            string r = la > lb ? a : b ;
            int k = la > lb ? la - 1 : lb - 1;
            //循环变量
            int ia = la - 1, ib = lb - 1;
            for (; ia >= 0 && ib >= 0; --ia, --ib)
            { 
                //转换为整数计算
                int temp = (a[ia] - '0') + (b[ib] - '0') + carry;
                if (temp >= 2)
                {
                    temp -= 2;
                    carry = 1;
                }
                else{
                    carry = 0;
                }//if
                //保存结果为相应字符类型
                r[k] = temp + '0';
                --k;
            }//while
    
            while (ia >= 0)
            {
                int temp = (a[ia] - '0') + carry;
                if (temp >= 2)
                {
                    temp -= 2;
                    carry = 1;
                }
                else{
                    carry = 0;
                }//if
                r[k] = temp + '0';
                --ia;
                --k;
            }//while
    
            while (ib >= 0)
            {
                int temp = (b[ib] - '0') + carry;
                if (temp >= 2)
                {
                    temp -= 2;
                    carry = 1;
                }
                else{
                    carry = 0;
                }//if
                r[k] = temp + '0';
                --ib;
                --k;
            }
    
            //若首位也有进位,则用"1"链接
            if (carry == 0)
                return r;
            else{
                return "1"+r;
            }
    
        }
    };
    

    GitHub测试程序源码

  • 相关阅读:
    Python-pymysql
    MySQL学习(3)
    MySQL学习(1)
    MySQL与PostgreSQL哪个更好?
    svn与git区别
    journalctl常用命令
    Spring Cloud 生产环境性能优化
    springcloud优雅停止上下线与熔断
    istio基础详解
    微服务的全链路监控
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214905.html
Copyright © 2011-2022 走看看