数组实现int随机数的阶乘(避免大数问题)

面试的一道题目,实现int随机数的阶乘。这道题就是考察你考没考虑大数问题,如何避免它。 我能想到的就是用数组去实现,然后写了一下代码。但是当i的值很大,接近Max_value时的情况还没有考虑到。

直接看代码:mul进行数组每一位的阶乘,carry()用来对数组的每一位进位,pos记录当前的数组有效位置。这道题还是用ArrayList写比较好,免得浪费空间(有空在更新)。

public class BigNumMul {
    public static void main(String args[]){
        SolutionBigNumMul s=new SolutionBigNumMul();
        s.mul(1000);
    }
}

class SolutionBigNumMul{

    public int res[]=new int[100000];
    public void mul(int num){
        int pos=1;//当前数组的有效位数+1;
        res[0]=1;
        for(int i=2;i<=num;i++){
            for(int j=0;j<pos;j++){
                res[j]=res[j]*i;
            }
            pos=Carry(res,pos);//把数组从index=0~pos-1,进位,然后更新pos的值。
        }
        StringBuffer sb=new StringBuffer();//用一个StringBuffer来显示大数
        for(int i=pos-1;i>=0;i--){
            sb.append(res[i]);
        }
        System.out.println(sb.toString());
    }
    public int Carry(int res[],int pos){
        int carry=0;int i=0;
        for(;i<=pos-1;i++){
            res[i]+=carry;
            if(res[i]<10){
                carry=0;
            }else if(res[i]>9&&i<pos-1){
                carry=res[i]/10;
                res[i]=res[i]%10;
            }else{
                while(res[i]>9){
                    carry=res[i]/10;
                    res[i]=res[i]%10;
                    i++;
                    res[i]=carry;
                }
            }
        }
        return i;
    }
}

 

转载于:https://www.cnblogs.com/codeLZC/p/10598744.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值