Leetcode每日随机2021/4/16

Leetcode每日随机2021/4/16

又来数学题啊,这打死我也做不出来啊,5种进位情况分类讨论,真有你的。
思路参考自此题解,这位老哥直接给5中分类画了个表,很清楚。
Leetcode每日随机2021/4/16

代码

class Solution {
    public int[] addNegabinary(int[] arr1, int[] arr2) {
		if (arr1.length == 1 && arr1[0] == 0) {
			return arr2;
		}
		if (arr2.length == 1 && arr2[0] == 0) {
			return arr1;
		}
		int carry = 0;
		int[] res = new int[1005];
		reverse(arr1);
		reverse(arr2);
		int idx = 0;
		while (idx < arr1.length || idx < arr2.length || carry != 0) {
			int sum = 0;
			if (idx >= arr1.length && idx >= arr2.length) {
				sum = carry;
			} else if (idx < arr1.length && idx >= arr2.length) {
				sum = carry + arr1[idx];
			} else if (idx >= arr1.length && idx < arr2.length) {
				sum = carry + arr2[idx];
			} else {
				sum = carry + arr1[idx] + arr2[idx];
			}
			switch (sum) {
			case -1:
				res[idx] = 1;
				carry = 1;
				break;
			case 0:
				res[idx] = 0;
				carry = 0;
				break;
			case 1:
				res[idx] = 1;
				carry = 0;
				break;
			case 2:
				res[idx] = 0;
				carry = -1;
				break;
			case 3:
				res[idx] = 1;
				carry = -1;
				break;
			}
            idx++;
		}
		int[] arr = null;
		for (int i = res.length - 1; i >= 0; i--) {
			if (res[i] == 1) {
				arr = new int[i + 1];
				System.arraycopy(res, 0, arr, 0, i + 1);
				break;
			}
		}
        if (arr == null) {
			return new int[] {0};
		}
		reverse(arr);
		return arr;
	}

	private void reverse(int[] arr) {
		for (int i = 0; i < arr.length / 2; i++) {
			int temp = arr[i];
			arr[i] = arr[arr.length - 1 - i];
			arr[arr.length - 1 - i] = temp;
		}
	}
}
上一篇:leetcode 345. 反转字符串中的元音字母


下一篇:js for循环的写法