Advertisement
Guest User

Untitled

a guest
Jan 11th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.43 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. char* multiply(char* str1, char* str2)
  6. {
  7.     int lb1 = strlen(str1);
  8.     int lb2 = strlen(str2);
  9.  
  10.     if (lb1 == 0 || lb2 == 0)
  11.         return "0";
  12.  
  13.     int* result = malloc((lb1+lb2) * sizeof(int));
  14.     for (int k = 0; k < (lb1+lb2); ++k){
  15.         result[k] = 0;
  16.     }
  17.  
  18.     int i_lb1 = 0;
  19.     int i_lb2 = 0;
  20.  
  21.     for (int i=lb1-1; i>=0; i--)
  22.     {
  23.         int trzym = 0;
  24.         int lb1 = str1[i] - '0';
  25.  
  26.         i_lb2 = 0;
  27.  
  28.         for (int j=lb2-1; j>=0; j--)
  29.         {
  30.             int lb2 = str2[j] - '0';
  31.  
  32.             int sum = lb1*lb2 + result[i_lb1 + i_lb2] + trzym;
  33.  
  34.             trzym = sum/10;
  35.  
  36.             result[i_lb1 + i_lb2] = sum % 10;
  37.  
  38.             i_lb2++;
  39.         }
  40.  
  41.         if (trzym > 0)
  42.             result[i_lb1 + i_lb2] += trzym;
  43.  
  44.         i_lb1++;
  45.     }
  46.  
  47.     int i = (lb1+lb2) - 1;
  48.     while (i>=0 && result[i] == 0)
  49.         i--;
  50.  
  51.     if (i == -1)
  52.         return "0";
  53.  
  54.     char* s;
  55.     s = malloc(i*sizeof(char));
  56.     s[0] = '\0';
  57.  
  58.     char *buffer = malloc(sizeof(char));
  59.     buffer[0] = '\0';
  60.     while (i >= 0){
  61.         sprintf(buffer,"%d",result[i--]);
  62.         strcat(s,buffer);
  63.     };
  64.  
  65.     free(buffer);
  66.     free(result);
  67.  
  68.     return s;
  69. }
  70.  
  71. int main()
  72. {
  73.     char* str1 = "12";
  74.     char* str2 = "12";
  75.  
  76.     printf("Wynik mnozenia dwoch liczb: ");
  77.     printf("%s\n",multiply(str1, str2));
  78.     return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement