Java实现:LeetCode负二进制数相加

  • 题目:
  • Java实现:LeetCode负二进制数相加_第1张图片
  • 代码:
  • public class text4 {
        public static void main(String[] args) {
            int[] arr1={1};
            int[] arr2={1};
            int[] arr = addNegabinary(arr1, arr2);
            for (int i=0;i arr1.length) {
                int[] temp = arr1;
                arr1 = arr2;
                arr2 = temp;
            }
    
            int temp,i,j;
            //从每个数组的末尾元素开始
            for(i = arr1.length - 1, j = arr2.length - 1; j > -1; j--, i--) {
                //对应位置的元素+1
                temp = arr1[i] + arr2[j];
                if(temp == 2) {
                    arr1[i] = 0;
                    if(i > 0 && arr1[i - 1] == 1) {
                        arr1[i - 1] = 0;
                        continue;
                    } else if(j > 0 && arr2[j - 1] == 1) {
                        arr2[j - 1] = 0;
                        continue;
                    }
                    temp = arr1.length - i;
                    arr1 = addOne(arr1, i - 1);
                    i = arr1.length - temp;
                    arr1 = addOne(arr1, i - 2);
                    i = arr1.length - temp;
                } else if(temp == 1) {
                    arr1[i] = 1;
                }
            }
            i = 0;
            while(i < arr1.length) {
                if(arr1[i++] != 0) {
                    break;
                }
            }
            //copyOfRange(): 将指定数组的指定范围复制到新数组中
            return Arrays.copyOfRange(arr1, i - 1, arr1.length);
        }
    
        private static int[] addOne(int[] arr, int index) {
            if(index < 0) {
                int[] result = new int[arr.length + 1];
                //arraycopy(): 将指定源数组中的数组从指定位置复制到目标数组的指定位置
                System.arraycopy(arr, 0, result, 1, arr.length);
                result[0] = 1;
                return result;
            }
    
            if(arr[index] == 0) {
                arr[index] = 1;
            } else {
                arr[index] = 0;
                if(index > 0 && arr[index - 1] == 1) {
                    arr[index - 1] = 0;
                    return arr;
                }
                int temp = arr.length - index;
                arr = addOne(arr, index - 1);
                index = arr.length - temp;
                arr = addOne(arr, index - 2);
            }
            return arr;
        }
    }
    
  • 结果:

你可能感兴趣的:(Java实现的算法)