• 清华机试-N的阶乘


    题目描述

     输入一个正整数N,输出N的阶乘。

    输入描述:

    正整数N(0<=N<=1000)

    输出描述:

     输入可能包括多组数据,对于每一组输入数据,输出N的阶乘
    示例1

    输入

    4
    5
    15
    

    输出

    24
    120
    1307674368000

    解题思路

    这道题目主要考察大数乘法。大数乘法的实现思路如下:

    1.定义一个向量,用于保存数a,数b各位相乘的结果,向量长度为lena + lenb;

    2.从大到小遍历向量,如果值加上进位大于等于10,则将值mod10,然后进位置为值 /10;

    3.如果第一个的值加上进位大于等于10,则增加一位。

    处理过程中还需要将数字转化为字符串,在C++11中提供了to_string(int)函数,如果要将字符串转化为数字,也有相应的函数。

    代码

    #include <iostream>
    #include <string>
    #include <vector>
    #include <sstream>
    
    using namespace std;
    
    void int2str(const int &int_temp,string &string_temp)
    {
            stringstream stream;
            stream<<int_temp;
            string_temp=stream.str();
    }
    
    string mul(string a,string b)
    {
        string res;
        int lena,lenb;
        lena = a.size();
        lenb = b.size();
        vector<int> tmp(lena + lenb - 1,0);
        for(int i = 0;i < lena;i++)
        {
            for(int j = 0;j < lenb;j++)
            {
                tmp[i+j] += (a[i] - '0') * (b[j] - '0');
            }
        }
        int carry = 0;
        for(int i = lena + lenb - 2;i >= 0;i--)
        {
            int num = carry + tmp[i];
            if(num >= 10)
            {
                carry = num / 10;
                tmp[i] = num % 10;
            }
            else
            {
                tmp[i] = num;
                carry = 0;
            }
        }
        if(carry > 0)
        {
            tmp.insert(tmp.begin(),carry);
        }
        for(auto i : tmp)
        {
            string temp = to_string(i);
            res = res + temp;
        }
        return res;
    }
    
    int main()
    {
        int a;
    //    cout << mul("120","6") << endl;
        while(cin >> a)
        {
            string res = "1";
            for(int i = a;i >= 1;i--)
            {
                string temp = to_string(i);
                res = mul(res,temp);
            }
            cout << res << endl;
        }
        return 0;
    }
    

      



  • 相关阅读:
    c++ 左值、右值;左值引用、右值引用
    leetcode 837 新21点
    c++ 继承和组合
    ubuntu 16.04 常用命令小结
    vim 常用命令小结(转)
    leetcode 1371. 每个元音包含偶数次的最长子字符串 (状压 + 前缀和 +hash)
    leetcode 974 和可被K整除的子数组
    leetcode 910 最小差值II
    关于 mysqladmin
    PHP闭包(Closure)初探
  • 原文地址:https://www.cnblogs.com/tracy520/p/8902863.html
Copyright © 2020-2023  润新知