fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. typedef struct Bigint{
  6. char *strnum;
  7. unsigned int length;
  8. }* Bigint;
  9.  
  10. void strrev(char *str, int len)
  11. {
  12. char cpy[len];
  13. int i, j;
  14. for(i = 0, j = len - 1; j >= 0; i++, j--){
  15. cpy[i] = str[j];
  16. }
  17. cpy[i] = '\0';
  18. strcpy(str, cpy);
  19. }
  20.  
  21. Bigint bigint_new(const char *strnum)
  22. {
  23. Bigint bigint = malloc(sizeof(Bigint));
  24. int len = strlen(strnum);
  25.  
  26. bigint->length = len;
  27. bigint->strnum = malloc(len+1);
  28.  
  29. strcpy(bigint->strnum, strnum);
  30.  
  31. return bigint;
  32. }
  33.  
  34. void bigint_del(Bigint bigint)
  35. {
  36. free(bigint->strnum);
  37. free(bigint);
  38. }
  39.  
  40. void bigint_show(Bigint bigint)
  41. {
  42. puts(bigint->strnum);
  43. }
  44.  
  45. Bigint bigint_add(Bigint big1, Bigint big2)
  46. {
  47. int length = (big1->length > big2->length ? big1->length : big2->length);
  48. char strnum[length + 1];
  49. memset(strnum, 0, length + 1);
  50.  
  51. int n, i1, i2, j = 0;
  52. for (i1 = big1->length, i2 = big2->length, j = 0;
  53. i1 >= 0 && i2 >= 0;
  54. --i1, --i2, ++j) {
  55. n = strnum[j] + (big1->strnum[i1] + big2->strnum[i2] - '0' * 2);
  56. if (n > 9) {
  57. strnum[j] = n % 10;
  58. strnum[j+1] = 1;
  59. }else{
  60. strnum[j] = n;
  61. }
  62. }
  63.  
  64. if(i1 > 0 && i2 <= 0){
  65. while(i1 >= 0){
  66. strnum[j++] += big1->strnum[i1--] - '0';
  67. }
  68. }else if(i1 <= 0 && i2 > 0){
  69. while(i2 >= 0){
  70. strnum[j++] += big2->strnum[i2--] - '0';
  71. }
  72. }
  73.  
  74. int i;
  75. for(i = 0; i < j; i++){
  76. strnum[i] += '0';
  77. }
  78.  
  79. strnum[j] = '\0';
  80. strrev(strnum, j);
  81.  
  82. return bigint_new(strnum);
  83. }
  84.  
  85. int main(void)
  86. {
  87. Bigint num1 = bigint_new("2134490128490823084023483024892");
  88. Bigint num2 = bigint_new("60981690786891763458749732985");
  89. Bigint num3 = bigint_add(num1, num2);
  90. bigint_show(num3);
  91.  
  92. return 0;
  93. }
  94.  
Success #stdin #stdout 0s 1964KB
stdin
Standard input is empty
stdout
2195471819277714847482232757877�