您的位置:首页 > 职场人生

黑马程序员——解题笔记(1)——求1000!的结果中包含多少个0

2014-12-18 20:44 363 查看
使用BigInteger的实现方法

package com.itheima;

import java.math.BigInteger;

/**
*  求1000!的结果中包含多少个0?注:1000! = 1×2×3×4×5×...×999×1000
*
* 思路:1.因为求出1000!之后数值太大,需要使用math.BigInteger,可以解决大数问题。
*     2.首先创建一个BigInteger对象,容纳计算结果。
*     3.for循环循环相乘。(1*(1+1)*(1+1+1)····*1000)
*     4.得出结果后,将BigInteger的对象用字符串表示。
*     5.for循环,使用str.charAt(i)方法搜寻有多少个0,有的话count++。
*     6.打印结果
*
*/
public class Test9 {
public static void main(String args[])
{
BigInteger result = new BigInteger("1");//新建一个值为1的BigInteger对象
int count = 0;//计数值为0

for(int i = 2 ; i <=1000 ; i++)
{
result = result.multiply(new BigInteger(i+""));//循环相乘,得出结果。
}
String str = result.toString();//将其变为string类型

for(int i = 0 ; i <str.length(); i++)//将结果(字符串)遍历一遍。
{
if(str.charAt(i) == '0')//当有"0"时候,count++作为计数。
{
count++;//计数,每有一个0就增加1.

}
}

System.out.println(count);//输出结果。
}
}


不用BigInteger的实现方法

此方法来自黑马论坛网友

import java.util.Arrays;

public class BigFactorial {
private static final int MAXDIGITS = 10000; // 能容纳的阶乘结果的最大位数
private static int digits; // n!的位数
private static int[] result = new int[MAXDIGITS]; // 阶乘结果的逆序

public static void main(String[] args) {
int n = 1000;
calFact(n);
printResult(n);
System.out.println("共包含 " + countAllZeroes() + " 个0,末尾有" + countTrailingZeroes() + "个0");
}

/**
* 计算n! = 1 * 2 *...* n,将n!的各位数逆序存入result数组中,并返回n!的位数。
* 计算原理:
*          2! = 2 * 1!; 3! = 3 * 2!; k! = k * (k-1)! 以此类推
*   k!的各位数以逆序方式存放在数组中,逆序存放的原因是方便处理乘积各位向高位的进位。
*           例如7!=5040,在数组中存储为0405。0405与8的乘积为
*                   个位:0*8                 = 0
*                   十位:(4*8)%10 + 个位进位0 = 2
*                   百位:0*8 + 十位进位3      = 3
*                   千位:(5*8)%10 + 百位进位0 = 0
*          万位:千位进位4            = 4
*          逆序后即为8!=40320
* @param n 大于等于0的整数
* @return n!结果的位数
*/
public static void calFact(int n) {
init(); // 初始化result和digits

int product = 0; // k!的第m位数与k+1的乘积,加上第m-1位数上的进位(k=1,2...n-1)
int carry = 0; // 进位
for (int i = 2; i <= n; i++) {
for (int j = 0; j < digits; j++) {
product = result[j] * i + carry;
carry = product / 10;
result[j] = product % 10;
if (j == digits - 1 && carry != 0) // 当前结果的最高位需要进位
digits++;
}
}
}

private static void init() {
Arrays.fill(result, 1, MAXDIGITS - 1, 0);
result[0] = 1;
digits = 1;
}

/**
* 逆序打印阶乘结果
* @param n
*/
public static void printResult(int n) {
System.out.print(n + "! = ");
for (int i = digits - 1; i >= 0; i--) {
System.out.print(result[i]);
}
System.out.println();
}

/**
* 统计阶乘结果中0的个数
* @return 阶乘结果中0的个数
*/
public static int countAllZeroes() {
int zeroCount = 0;
for (int i = digits - 1; i >= 0; i--) {
if (result[i] == 0)
zeroCount++;
}
return zeroCount;
}

/**
* 统计阶乘结果末尾0的个数
* @return 阶乘结果末尾0的个数
*/
public static int countTrailingZeroes() {
int zeroCount = 0;
for (int i = 0; i < digits; i++)
if (result[i] == 0)
zeroCount++;
else
break;
return zeroCount;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐