zoukankan      html  css  js  c++  java
  • 【leetcode】67. Add Binary

    @requires_authorization
    @author johnsondu
    @create_time 2015.7.15 11:00
    @url [add binary](https://leetcode.com/problems/add-binary/)
    /*******************
     *  模拟大数相加
     *  时间复杂度: O(n)
     *  空间复杂度: O(n)
     ******************/
    class Solution {
    public:
        string addBinary(string a, string b) {
            int lena = a.size();
            int lenb = b.size();
            string ans = "";
            string tmpa = "";
            string tmpb = "";
            for(int i = lena-1; i >= 0; i --) tmpa += a[i];
            for(int i = lenb-1; i >= 0; i --) tmpb += b[i];
            int mins = min(lena, lenb);
            int carry = 0;
            for(int i = 0; i < mins; i ++){
                int res = (tmpa[i] - '0') + (tmpb[i] - '0') + carry; 
                carry = res > 1 ?

    1 : 0; res = res % 2; ans += (res + '0'); } for(int i = mins; i < lena; i ++){ int res = (tmpa[i] - '0') + carry; carry = res > 1 ?

    1 : 0; res = res % 2; ans += (res + '0'); } for(int i = mins; i < lenb; i ++){ int res = (tmpb[i] - '0') + carry; carry = res > 1 ?

    1 : 0; res = res % 2; ans += (res + '0'); } if(carry){ ans += (carry + '0'); } int len_ans = ans.size(); for(int i = 0; i < len_ans / 2; i ++){ char tmp = ans[i]; ans[i] = ans[len_ans-i-1]; ans[len_ans-i-1] = tmp; } return ans; } };

    // Simplified Version
    class Solution {
    public:
        string addBinary(string a, string b) {
            int lena = a.size() - 1;
            int lenb = b.size() - 1;
            string ans = "";
            int carry = 0;
            while(lena >= 0 || lenb >= 0 || carry > 0){
                int res = carry;
                if(lena >= 0) res += (a[lena] - '0');
                if(lenb >= 0) res += (b[lenb] - '0');
    
                carry = res / 2;
                ans = string(1, (res & 1) + '0') + ans;
                lena --;
                lenb --;
            }
            return ans;
        }
    };
  • 相关阅读:
    H5开发推荐使用Q.js,轻量的前端单页路由框架
    微信公众号分享接口
    ios浏览器 图片size过大(长度6000px) 设置translateZ(0)/translate3d(0,0,0),会模糊
    Android Studio创建项目
    unity 旋转两种方法
    Unity3D 物体移动方法总结
    unity3d 各键值对应代码
    MonoBehaviour简述
    unity之Rigidbody属性
    Unity UGUI实现分段式血条
  • 原文地址:https://www.cnblogs.com/yfceshi/p/7063065.html
Copyright © 2011-2022 走看看