IDEA2023.1.3破解,IDEA破解,IDEA 2023.1破解,最新IDEA激活码

二进制求和

IDEA2023.1.3破解,IDEA破解,IDEA 2023.1破解,最新IDEA激活码

二进制求和

给你两个二进制字符串,返回它们的和(用二进制表示)。
输入为 非空 字符串且只包含数字10

示例

输入: a = "11", b = "1"
输出: "100"

输入: a = "1010", b = "1011"
输出: "10101"

提示

  • 每个字符串仅由字符'0''1'组成。
  • 1 <= a.length, b.length <= 10^4
  • 字符串如果不是"0",就都不含前导零。

题解

/**
 * @param {string} a
 * @param {string} b
 * @return {string}
 */
var addBinary = function(a, b) {
    var longer = "";
    var shorter = "";
    if(a.length > b.length){
        longer = a;
        shorter = b.padStart(a.length,0);
    }else{
        longer = a.padStart(b.length,0);
        shorter = b;
    }
    var target = "";
    var addition = 0;
    for(let i=longer.length-1;i>=0;--i){
        let unitNum = ~~(longer[i]) + ~~(shorter[i]) + addition;
        addition = 0;
        if(unitNum >= 2) {
            addition = 1;
            target = `${unitNum-2}${target}`;
        }else{
            target = `${unitNum}${target}`;
        }
    }
    if(addition) target = `1${target}`;
    return target;
};

思路

首先需要将两个字符串的长度进行统一,判断两个字符串长度的长度,然后选出短的字符串在字符串前填充0,也就是使用String.prototype.padStart()方法进行填充,然后定义目标字符串以及进位标记变量,然后从后开始往前遍历字符串,将字符串中的字符转换成数字类型然后相加并与进位变量相加,其中~~就是利用位运算将字符转换成数字,相加完成后将进位标志置为0,然后判断字符是否大于2,如果大于等于2则将相加的字符减掉2并将进位标记记为1,若小于2则直接拼接字符串,然后不断循环完成目标字符的拼接,若最后依然有进位标志,则直接拼接1到目标字符串前,然后返回目标字符串即可。

每日一题

https://github.com/WindrunnerMax/EveryDay

题源

https://leetcode-cn.com/problems/add-binary

文章永久链接:https://tech.souyunku.com/?p=39655


Warning: A non-numeric value encountered in /data/wangzhan/tech.souyunku.com.wp/wp-content/themes/dux/functions-theme.php on line 1154
赞(99) 打赏



未经允许不得转载:搜云库技术团队 » 二进制求和

IDEA2023.1.3破解,IDEA破解,IDEA 2023.1破解,最新IDEA激活码
IDEA2023.1.3破解,IDEA破解,IDEA 2023.1破解,最新IDEA激活码

评论 抢沙发

大前端WP主题 更专业 更方便

联系我们联系我们

觉得文章有用就打赏一下文章作者

微信扫一扫打赏

微信扫一扫打赏


Fatal error: Uncaught Exception: Cache directory not writable. Comet Cache needs this directory please: `/data/wangzhan/tech.souyunku.com.wp/wp-content/cache/comet-cache/cache/https/tech-souyunku-com/index.q`. Set permissions to `755` or higher; `777` might be needed in some cases. in /data/wangzhan/tech.souyunku.com.wp/wp-content/plugins/comet-cache/src/includes/traits/Ac/ObUtils.php:367 Stack trace: #0 [internal function]: WebSharks\CometCache\Classes\AdvancedCache->outputBufferCallbackHandler() #1 /data/wangzhan/tech.souyunku.com.wp/wp-includes/functions.php(5109): ob_end_flush() #2 /data/wangzhan/tech.souyunku.com.wp/wp-includes/class-wp-hook.php(303): wp_ob_end_flush_all() #3 /data/wangzhan/tech.souyunku.com.wp/wp-includes/class-wp-hook.php(327): WP_Hook->apply_filters() #4 /data/wangzhan/tech.souyunku.com.wp/wp-includes/plugin.php(470): WP_Hook->do_action() #5 /data/wangzhan/tech.souyunku.com.wp/wp-includes/load.php(1097): do_action() #6 [internal function]: shutdown_action_hook() #7 {main} thrown in /data/wangzhan/tech.souyunku.com.wp/wp-content/plugins/comet-cache/src/includes/traits/Ac/ObUtils.php on line 367