that_one_nigga_you_k

soma de strings

Nov 8th, 2023
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.67 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. int main() {
  6.     char *num, *nam, *result;
  7.     int carry = 0;
  8.  
  9.     num = (char*)malloc(100000000 * sizeof(char));
  10.     nam = (char*)malloc(100000000 * sizeof(char));
  11.     result = (char*)malloc(100000001 * sizeof(char));
  12.  
  13.     if (num == NULL || nam == NULL || result == NULL) {
  14.         printf("alocação faiou\n");
  15.         return 1;
  16.     }  
  17.  
  18.     printf("digite o primeiro numero: ");
  19.     scanf(" %[^\n]s", num);
  20.     printf("\ndigite o segundo numero: ");
  21.     scanf(" %[^\n]s", nam);
  22.  
  23.     printf("\n\n%d\n%d\n\n", (int)strlen(num), (int)strlen(nam));
  24.  
  25.     int loopMax, loopMin;
  26.  
  27.     int len1 = strlen(num);
  28.     int len2 = strlen(nam);
  29.  
  30.     loopMax = (len1 > len2) ? len1 : len2;
  31.     loopMin = (len1 > len2) ? len2 : len1;
  32.  
  33.     for(int i = 0; i < loopMax; i++){
  34.         int digit1 = (i < len1) ? num[len1 - i - 1] - '0' : 0;
  35.         int digit2 = (i < len2) ? nam[len2 - i - 1] - '0' : 0;
  36.         int sum = digit1 + digit2 + carry;
  37.  
  38.         carry = sum/10;
  39.         result[i] = (sum%10) + '0';
  40.     }
  41.  
  42.     if (carry > 0) {
  43.         result[loopMax] = carry + '0';  // Add the final carry as the most significant digit
  44.         result[loopMax + 1] = '\0';     // Null-terminate the result
  45.     } else {
  46.         result[loopMax] = '\0';         // Null-terminate the result
  47.     }
  48.  
  49.     // Reverse the result
  50.     int resultLen = strlen(result);
  51.     for (int i = 0, j = resultLen - 1; i < j; i++, j--) {
  52.         char temp = result[i];
  53.         result[i] = result[j];
  54.         result[j] = temp;
  55.     }
  56.  
  57.     printf("\nResult: %s\n", result);
  58.  
  59.     free(num);
  60.     free(nam);
  61.     free(result);
  62.  
  63.     return(0);
  64. }
Add Comment
Please, Sign In to add comment