teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

4

add を少し変えてみた

2021/11/17 18:32

投稿

jimbe
jimbe

スコア13357

answer CHANGED
@@ -44,15 +44,16 @@
44
44
 
45
45
  // a+=b
46
46
  int add(Value *a, Value *b, int n) {
47
+ a->l = max(a->l, b->l);
47
- for(int i=0; i<max(a->l, b->l); i++) {
48
+ for(int i=0; i<a->l; i++) {
48
49
  a->d[i] += b->d[i];
49
50
  if(a->d[i] >= 10) {
51
+ a->d[i] -= 10;
50
52
  if(i+1 >= n) return FALSE; //overflow
51
- a->d[i+1] += a->d[i] / 10;
52
- a->d[i] %= 10;
53
+ a->d[i+1] ++;
54
+ a->l = max(a->l, i+2);
53
55
  }
54
56
  }
55
- for(int i=0; i<n; i++) if(a->d[i] > 0) a->l = i+1;
56
57
  return TRUE; //success
57
58
  }
58
59
 
@@ -70,7 +71,7 @@
70
71
 
71
72
  while(add(a, b, n)) swap(&a, &b);
72
73
  //print("a=", a);
73
- print("", b);
74
+ print("", b); //83621143489848422977
74
75
 
75
76
  vlfree(a);
76
77
  vlfree(b);

3

calloc の使い方間違いなど修正

2021/11/17 18:32

投稿

jimbe
jimbe

スコア13357

answer CHANGED
File without changes

2

calloc の使い方間違いなど修正

2021/11/17 07:33

投稿

jimbe
jimbe

スコア13357

answer CHANGED
File without changes

1

calloc の使い方間違いなど修正

2021/11/17 07:33

投稿

jimbe
jimbe

スコア13357

answer CHANGED
@@ -2,7 +2,6 @@
2
2
  ```c
3
3
  #include <stdio.h>
4
4
  #include <stdlib.h>
5
- #include <memory.h>
6
5
 
7
6
  #define TRUE 1
8
7
  #define FALSE 0
@@ -13,12 +12,11 @@
13
12
  } Value;
14
13
 
15
14
  Value *vlalloc(int n, int i) {
16
- Value *v = calloc(sizeof(Value)+sizeof(char)*n, 1);
15
+ Value *v = calloc(1, sizeof(Value)+sizeof(char)*n);
17
16
  if(v == NULL) {
18
17
  printf("cannot allocate memory.\n");
19
18
  exit(1);
20
19
  }
21
- memset(v->d, 0, sizeof(char)*n);
22
20
  v->d[0] = i;
23
21
  v->l = 1;
24
22
  return v;
@@ -70,7 +68,7 @@
70
68
  Value *a = vlalloc(n, 0);
71
69
  Value *b = vlalloc(n, 1);
72
70
 
73
- while(add(a, b, n)) swap(&a,&b);
71
+ while(add(a, b, n)) swap(&a, &b);
74
72
  //print("a=", a);
75
73
  print("", b);
76
74