LeetCode·Pregunta diaria·1073. Suma negativa de números binarios·Simulación

Autor: Xiao Xun
Enlace: https://leetcode.cn/problems/adding-two-negabinary-numbers/solutions/2274400/mo-ni-zhu-shi-chao-ji-xiang-xi-by-xun-ge- g3zo/
Fuente: Los derechos de autor de LeetCode
pertenecen al autor. Para reimpresión comercial, comuníquese con el autor para obtener autorización, para reimpresión no comercial, indique la fuente.

tema

 

tren de pensamiento

Recorremos los dos arreglos, comenzando desde el bit más bajo, registramos los dígitos actuales de los dos arreglos como a y b, el acarreo es c, y el resultado de sumar los tres números es x.

  • Si x ≥ 2 , resta 2 de x y lleva −1 al bit alto. Es decir, cada 2 avanza y pierde 1.
  • Si x = −1, establezca x en 1 y lleve 1 al bit alto.
  • Si no es así, x no se procesa y el acarreo es 0

Luego agregamos x a la matriz de respuesta y pasamos al siguiente bit.

Después del recorrido, elimine el 0 al final de la matriz de respuesta e invierta la matriz para obtener la respuesta final.

el código


void reverse(int *arr, int left, int right) {//翻转数组元素
    while (left < right) {
        int tmp = arr[left];
        arr[left] = arr[right];
        arr[right] = tmp;
        left++;
        right--;
    }
}

int* addNegabinary(int* arr1, int arr1Size, int* arr2, int arr2Size, int* returnSize){
    int i = arr1Size - 1, j = arr2Size - 1;
    int *ans = (int *)calloc(arr1Size + arr2Size + 1, sizeof(int));
    int pos = 0;//初始化变量
    for (int c = 0; i >= 0 || j >= 0 || c; --i, --j) {
        int a = i < 0 ? 0 : arr1[i];
        int b = j < 0 ? 0 : arr2[j];//防止数组溢出
        int x = a + b + c;//加法

        if (x >= 2) {//情况一
            x -= 2;
            c = -1;
        } else if (x == -1) {//情况二
            x = 1;
            c = 1;
        } else {//情况三
            c = 0;
        }

        ans[pos++] = x;//加入数组
    }
    while (pos > 1 && ans[pos - 1] == 0) {//去除0
        pos--;
    }
    *returnSize = pos;
    reverse(ans, 0, pos - 1);//翻转
    return ans;
}

作者:小迅
链接:https://leetcode.cn/problems/adding-two-negabinary-numbers/solutions/2274400/mo-ni-zhu-shi-chao-ji-xiang-xi-by-xun-ge-g3zo/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

Supongo que te gusta

Origin blog.csdn.net/m0_64560763/article/details/130741751
Recomendado
Clasificación