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. if(strnum[j+1] != 0){
  75. j++;
  76. }
  77.  
  78. int i;
  79. for(i = 0; i < j; i++){
  80. strnum[i] += '0';
  81. }
  82.  
  83. strnum[j] = '\0';
  84. strrev(strnum, j);
  85.  
  86. return bigint_new(strnum);
  87. }
  88.  
  89. int main(void)
  90. {
  91. Bigint num1 = bigint_new("990");
  92. Bigint num2 = bigint_new("900");
  93. Bigint num3 = bigint_add(num1, num2);
  94. bigint_show(num3);
  95.  
  96. return 0;
  97. }
  98.  
Success #stdin #stdout 0s 1964KB
stdin
Standard input is empty
stdout
1890�