zoukankan      html  css  js  c++  java
  • 算法笔记-----大整数相乘---数组实现

     1 //
     2 // Created by alim on 2017/12/18.
     3 //
     4 
     5 #include "dazs.h"
     6 #include<stdio.h>
     7 #include<stdlib.h>
     8 #include<string.h>
     9 #define NUM_LEN   50//数字的最大长度
    10 
    11 int main()
    12 {
    13     int i, n, temp = 0, p, k;
    14 
    15     char num1[NUM_LEN], num2[NUM_LEN];
    16     puts("Please input the first number:");
    17     gets(num1);
    18     puts("
    Please input the second number:");
    19     gets(num2);
    20     int len1 = strlen(num1);
    21     int len2 = strlen(num2);
    22     int *arr1 = (int *)malloc(sizeof(int) * len1);
    23     int *arr2 = (int *)malloc(sizeof(int) * len2);
    24 
    25     for(i = 0; i < len1; i++)
    26     {
    27         arr1[i] = (int)num1[i] - 48;   //把字符转换成对应的整数
    28     }
    29     for(i = 0; i < len2; i++)
    30     {
    31         arr2[i] = (int)num2[i] - 48;
    32     }
    33 
    34     int *result = (int *)malloc(sizeof(int) * (len1 + len2));
    35     n = len1 + len2 - 1;
    36     for(i = 0; i <= n; i++)
    37     {
    38         result[i] = 0;   //初始化结果数组
    39     }
    40 
    41     for(i = len1 - 1; i >= 0; i--)
    42     {
    43         p = arr1[i];
    44         for(k = len2 - 1; k >= 0; k--)
    45         {
    46             temp = result[n] + p * arr2[k];
    47             if(temp >= 10)   //如果temp>=10,则应该进位
    48             {
    49                 result[n] = temp%10;   //取个位
    50                 result[n - 1] += temp/10;   //向前进位
    51             }
    52             else
    53             {
    54                 result[n] = temp;
    55             }
    56             n--;
    57         }
    58         n = n + len2 - 1;   //回退 len2 - 1 位
    59     }
    60 
    61     //输出计算结果
    62     puts("
    The calulation results is:");
    63     if(result[0] != 0)
    64     {
    65         printf("%d",result[0]);
    66     }
    67     for(i = 1; i <= len1 +len2 -1; i++)
    68     {
    69         printf("%d", result[i]);
    70     }
    71     printf("
    
    ");
    72     return 0;
    73 }
  • 相关阅读:
    tensorflow源码解析之framework-shape_inference
    tensorflow源码解析之framework-function
    tensorflow源码解析之framework-device
    时间之外的往事
    字段初始值无法引用非静态字段、方法或属性“ ”
    第六期新人助跑感悟
    java volatile
    spring aop
    jvm类加载机制
    redis 集群 sharding策略
  • 原文地址:https://www.cnblogs.com/alimjan/p/8079413.html
Copyright © 2011-2022 走看看