zoukankan      html  css  js  c++  java
  • 大数乘法

    H - Product

    The problem is to multiply two integers X, Y. (0<=X,Y<10250)

    Input

    The input will consist of a set of pairs of lines. Each line in pair contains one multiplyer.

    Output

    For each input pair of lines the output line should consist one integer the product.

    Sample Input
    12
    12
    2
    222222222222222222222222
    Sample Output
    144
    444444444444444444444444

    思路:因为乘法还是需要进位的所以要转int数组倒叙存储。。
    再新开个数组记录结果(注意要初始化)
    根据乘法的特点需要用两个for循环来记录每一位上的数。。。(注意先不要进位,,,乘法算完后统一进位)
    #include <iostream>
    #include <stdio.h>
    #include <string.h>
    #include <algorithm>
    #include <string>
    #include <cstring>
    using namespace std;
    const int N = 10000 ;
    
    
    void multiply(char *a , char *b)
    {
        int c[N] , d[N] , e[N];
        memset(e , 0 , sizeof(c));
        int len1 = strlen(a) , len2 = strlen(b) ;
        int jj = 0 ;
        for(int i = len1 - 1 ; i >= 0 ; i--)
            c[jj++] = a[i] - '0' ;
        jj = 0 ;
        for(int i = len2 - 1 ; i >= 0 ; i--)
            d[jj++] = b[i] - '0' ;
        int k = 0 ;
        for(int i = 0 ; i < len1  ; i++)
        {
    
            for(int j = 0 ; j < len2  ; j++)
            {
                e[i+j] += c[i] * d[j] ;
            }
        }
        int len = len1 + len2 , x  ;//这个len是相乘完之后的可能的最长的长度。。。之后可通过去前置零缩短长度
    
        for(int i = 0 ; i < len ; i++)
        {
            x = e[i] ;
            e[i] = (e[i] + k) % 10 ;
            k = (x + k) / 10 ;
    
        }
        for(int i = len - 1 ; i >= 0 ; i--)
        {
            if(e[i] == 0)//去前置零
            {
                len -- ;
            }
            else{
                break ;
            }
        }
        if(len == 0)
            cout << 0 << endl ;
        else
        {
            for(int i = len - 1 ; i >= 0 ; i --)
            cout << e[i] ;
            cout << endl ;
        }
    
    }
    
    
    int main()
    {
        char a[N] , b[N] , c[N] ;
        while(~scanf("%s%s" , &a , &b))
        {
            multiply(a , b);
        }
    
        return 0;
    }


  • 相关阅读:
    概率统计(DP)
    iOS中几种定时器
    微信开发笔记——微信网页登录授权,获取用户信息
    swift中通知的使用
    Swift的基础,操作符,字符串和集合类型
    NSNotificationCenter
    IOS中通知中心(NSNotificationCenter)的使用总结
    Swift观察者模式
    swift中通知的使用
    Swift
  • 原文地址:https://www.cnblogs.com/nonames/p/11203595.html
Copyright © 2011-2022 走看看