Chinaunix首页 | 论坛 | 博客
  • 博客访问: 204159
  • 博文数量: 24
  • 博客积分: 608
  • 博客等级: 中士
  • 技术积分: 371
  • 用 户 组: 普通用户
  • 注册时间: 2012-04-22 21:10
文章分类

全部博文(24)

文章存档

2012年(24)

分类: C/C++

2012-09-19 10:54:36


点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <string.h>

  3. #define SIZE 1024

  4. void multiply(const char *num1, const char *num2, char *result)
  5. {
  6.     if(num1 == NULL || num2 == NULL)
  7.         return ;
  8.     
  9.     //判断0
  10.     if(num1[0] == '0' || num2[0] == '0')
  11.     {
  12.         result[0] = '0';
  13.         return;
  14.     }

  15.     int isNegative = 1;
  16.     int beg1 = 0, beg2 = 0, end1 = strlen(num1) - 1, end2 = strlen(num2) - 1;
  17.     int i, j, k = 0;
  18.     int carry = 0, record = 0;
  19.     int mult1 = 0, mult2 = 0, mult = 0;
  20.     
  21.     //判断符号
  22.     if(num1[0] == '-' && num2[0] != '-')
  23.     {
  24.         isNegative = -1;
  25.         beg1++;
  26.     }
  27.     else if(num1[0] != '-' && num2[0] == '-')
  28.     {
  29.         isNegative = -1;
  30.         beg2++;
  31.     }
  32.     else if(num1[0] == '-' && num2[0] == '-')
  33.     {
  34.         isNegative = 1;
  35.         beg1++;
  36.         beg2++;
  37.     }
  38.     else
  39.         isNegative = 1;

  40.     //两大数相乘
  41.     for(i = end1; i >= beg1; i--)
  42.     {
  43.         if(num1[i] >= '0' && num1[i] <= '9')
  44.             mult1 = num1[i] - '0';
  45.         k = record++;
  46.         carry = 0;
  47.         for(j = end2; j >= beg2; j--)
  48.         {
  49.             if(num2[j] >= '0' && num2[j] <= '9')
  50.                 mult2 = num2[j] - '0';
  51.             if(result[k] == 0)
  52.                 result[k] += '0';
  53.             mult = mult1 * mult2 + carry + result[k] - '0';
  54.             result[k++] = mult % 10 + '0';
  55.             carry = mult / 10;
  56.         }
  57.         if(carry > 0)
  58.             result[k++] = carry + '0';
  59.     }
  60.     
  61.     //如果是负数
  62.     if(isNegative == -1)
  63.     {
  64.         result[k++] = '-';
  65.     }
  66.     
  67.     //字符串逆序
  68.     i = 0;
  69.     j = strlen(result) - 1;
  70.     for(; i <= j; i++, j--)
  71.     {
  72.         char c = result[i];
  73.         result[i] = result[j];
  74.         result[j] = c;
  75.     }
  76. }

  77. int main()
  78. {
  79.     char num1[SIZE] = "-990";
  80.     char num2[SIZE] = "102030409";
  81.     char result[SIZE];
  82.     memset(result, 0, sizeof(result));
  83.     multiply(num1, num2, result);
  84.     printf("%s\n", result);
  85. }

阅读(1935) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~