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;
    }
  • 相关阅读:
    iOS 获取项目名称及版本号
    Xcode 使用自定义字体
    自己制作精美的App Store 软件截屏
    iOS 数据持久性存储-对象归档
    iOS 数据持久性存储-属性列表
    好长时间没回来了,回归本位!
    VBA删除表格最后一行
    VBA表格单元格替换文字
    VBA添加表格
    oracle语句
  • 原文地址:https://www.cnblogs.com/swblog/p/3328336.html
Copyright © 2011-2022 走看看