c语言:大数相加

#define MAX_LENGTH 10000

void add(char * a, char * b, char res[])
{
  int result[MAX_LENGTH + 1] = {0};
  int t1[MAX_LENGTH] = {0};
  int t2[MAX_LENGTH] = {0};
  
  int len1= strlen(a);
  int len2= strlen(b);
  int len ;


  if (len1 > len2)
  {
    len = len1;
  }
  else
  {
    len = len2;
  }

  for(int i = 0, j = len1 - 1; j >= 0; i++, j--)
  {
    t1[i] = a[j] - '0';
  }

  for (int i = 0, j = len2 - 1; j >= 0; i++, j--)
  {
    t2[i] = b[j] - '0';
  }

  for(int i=0; i < len; i++)
  {
    result[i] += t1[i] + t2[i];
    if (result[i] > 9)
    {
      result[i+1]++;
      result[i]-=10;
    }
  }

  if (result[len] > 0)
  {
    len++;
  }
  
  for(int i = len - 1, j = 0; i >= 0; i--,j++)
  {
    res[j] = result[i] + '0';
  }
}

使用:

  char res[MAX_LENGTH + 1] = {'0'};
  add(n1, n2, res);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是C语言链表实现大数相加的示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct Node { int val; struct Node *next; } Node; Node *createNode(int val) { Node *node = (Node*)malloc(sizeof(Node)); node->val = val; node->next = NULL; return node; } void insertNode(Node **head, int val) { Node *node = createNode(val); node->next = *head; *head = node; } void printList(Node *head) { while (head) { printf("%d", head->val); head = head->next; } printf("\n"); } Node *addTwoNumbers(Node *l1, Node *l2) { Node *dummyHead = createNode(0); Node *cur = dummyHead; int carry = 0; while (l1 || l2 || carry) { int sum = carry; if (l1) { sum += l1->val; l1 = l1->next; } if (l2) { sum += l2->val; l2 = l2->next; } carry = sum / 10; cur->next = createNode(sum % 10); cur = cur->next; } return dummyHead->next; } int main() { char str1[100], str2[100]; scanf("%s%s", str1, str2); int len1 = strlen(str1), len2 = strlen(str2); Node *l1 = NULL, *l2 = NULL; for (int i = len1 - 1; i >= 0; i--) { insertNode(&l1, str1[i] - '0'); } for (int i = len2 - 1; i >= 0; i--) { insertNode(&l2, str2[i] - '0'); } Node *res = addTwoNumbers(l1, l2); printList(res); return 0; } ``` 该程序首先读入两个字符串表示的大数,然后将其转换为链表形式。接着使用链表实现的加法将两个链表相加,最后输出相加结果的链表形式。 该程序使用了链表的基本操作,如创建节点、插入节点、遍历节点等。其中 `addTwoNumbers` 函数实现了链表的加法,每次取出两个链表的对应结点以及进位值,计算其和并构造新的节点,最后连接到结果链表中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值