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
}
}