zoukankan      html  css  js  c++  java
  • 字符串表示的大整数相乘

    题目要求:

    设计一大整数相乘的函数,函数原型int multiply(char *strNum1,char *strNum2, char *strRslt),strNum1是字符串表示的被乘数,strNum2是字符串表示的乘数,strRslt用来存放乘积结果的字符串。

    例如:strNum1 = “2345678901234”;
            strNum2 = "23456789"

    乘积结果,strRslt="55022095047997777626"

    函数实现:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    int multiply(char *strNum1,char *strNum2, char *strRslt) 
    {  
        int i,j,carry,t,tt;  
        int len1, len2;
        int rslt_index = 0;
        if(strNum1 == NULL || strNum2 == NULL || strRslt == NULL)
            return -1;
        len1 = strlen(strNum1);
        len2 = strlen(strNum2);
        memset(strRslt, 0 ,len1+len2);//把存放结果的空间先清零
        for(i = 0; i < len2; i++)  
        {  
            carry = 0;  
            for(j = 0; j < len1; j++)  
            {      
                t = (strNum1[len1-1-j]-'0')*(strNum2[len2-1-i]-'0')+carry;//从最低位开始计算  
                  if(0 == t)
                    continue;                  
                rslt_index = j+i;          
                tt = strRslt[rslt_index] + t;      
                strRslt[rslt_index] = tt % 10;      
                carry = tt / 10;  
            }  
            if(carry > 0)
            {  
                strRslt[++rslt_index] += carry;  
            }  
        }
        //反串
        for(i = 0; i <=rslt_index/2; i++)
        {
            t = strRslt[i] + '0';
            strRslt[i] = strRslt[rslt_index-i] + '0';
            strRslt[rslt_index-i] = t;
        } 
        return 0;
    }  
    
    int main(void)
    {
        char a[20] = {0}; 
        char b[20] = {0}; 
        char result[50] = {0}; 
        
        printf("Pls input first integer:");
        scanf("%s",a);
        printf("Pls input second integer:");
        scanf("%s",b);
        multiply(a, b, result);
        printf("result is:%s
    ",result);
        return 0;
    }
  • 相关阅读:
    P4556 [Vani有约会]雨天的尾巴(线段树合并)
    bzoj3590: [Snoi2013]Quare
    P3187 [HNOI2007]最小矩形覆盖
    对文件中的名字进行随机抽选(小脚本)
    用shell编写一个三角形图案
    HUE安装与使用
    史上最全CentOS6离线安装部署Cloudera Manager5.9.3
    ReLU 函数
    关于反向传播
    关于微分
  • 原文地址:https://www.cnblogs.com/swblog/p/3328336.html
Copyright © 2011-2022 走看看