Lintcode 729. 阶乘除法的最后一位数

描述

给出两个数 A 和 B, 其中 B >= A. 我们需要计算结果 F 的最后一位数是什么, 其中F = B! / A!(1 <= A, B <= 10^18, A 和 B 非常大)

样例

给出 A = 2, B = 4, 返回 2
A! = 2 以及 B! = 24, F = 24 / 2 = 12 --> 最后一位数为 2 

给出 A = 107, B = 109, 返回 2

思路:分析下各种情况就可以了,简单题
 1 class Solution {
 2 public:
 3     /**
 4      * @param A: the given number
 5      * @param B: another number
 6      * @return: the last digit of B! / A! 
 7      */
 8     int computeLastDigit(long long A, long long B) {
 9         // write your code here
10         if(A > B) return 0;
11         if(A == B) return 1;
12         if(B - A >= 10) return 0;//超过10个连续数字最后一位肯定0
13         int x = A%10;
14         int y = B%10;
15         if(x > y) return 0;//是否包含0判断一下
16         int res = 1;
17         for(int i = x + 1; i <= y; ++i){
18             res *= i;
19         }
20         return res%10;
21     }
22 };

猜你喜欢

转载自www.cnblogs.com/J1ac/p/9062025.html