LeetCode每日一题(1073. Adding Two Negabinary Numbers)

给定两个负二进制数arr1和arr2,返回它们相加的结果。每个数以数组形式表示,从最高位到最低位,且没有前导零。题目要求返回相加结果同样为没有前导零的数组形式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given two numbers arr1 and arr2 in base -2, return the result of adding them together.

Each number is given in array format: as an array of 0s and 1s, from most significant bit to least significant bit. For example, arr = [1,1,0,1] represents the number (-2)^3 + (-2)^2 + (-2)^0 = -3. A number arr in array, format is also guaranteed to have no leading zeros: either arr == [0] or arr[0] == 1.

Return the result of adding arr1 and arr2 in the same format: as an array of 0s and 1s with no leading zeros.

Example 1:

Input: arr1 = [1,1,1,1,1], arr2 = [1,0,1]
Output: [1,0,0,0,0]

Explanation: arr1 represents 11, arr2 represents 5, the output represents 16.

Example 2:

Input: arr1 = [0], arr2 = [0]
Output: [0]

Example 3:

Input: arr1 = [0], arr2 = [1]
Output: [1]

Constraints:

  • 1 <= arr1.length, arr2.length <= 1000
  • arr1[i] and arr2[i] are 0 or 1
  • arr1 and arr2 have no leading zeros

这题真不知道该怎么表达, 看代码吧


impl Solution {
    pub fn add_negabinary(mut arr1: Vec<i32>, mut arr2: Vec<i32>) -> Vec<i32> {
        arr1.reverse();
        arr2.reverse();
        let mut ho = 0;
        let max_length = arr1.len().max(arr2.len());
        let mut ans = vec![0; max_length + 2];
        for i in 0..ans.len() {
            let d1 = *arr1.get(i).unwrap_or(&0);
            let d2 = *arr2.get(i).unwrap_or(&0);
            // 当前位相加然后减去进位, 因为2的偶数次方是正数, 奇数次方是负数,所以前一位进上来的与当前位的正负性是相反的,所以是减操作
            let curr = d1 + d2 - ho;
            match curr {
                3 => {
                    ans[i] = 1;
                    ho = 1;
                }
                2 => {
                    ans[i] = 0;
                    ho = 1;
                }
                1 => {
                    ans[i] = 1;
                    ho = 0;
                }
                0 => {
                    ans[i] = 0;
                    ho = 0;
                }
                // 这里其实是当前值-1的情况,当前位置1,然后要像后一位借1, 因为相邻两位之间的正负性相反所以这里要把进位标成-1
                _ => {
                    ans[i] = 1;
                    ho = -1;
                }
            }
        }
        while ans.len() > 1 && *ans.last().unwrap() == 0 {
            ans.pop();
        }
        ans.reverse();
        ans
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值