Math problems
172. Factorial Trailing Zeroes
Given an integer n, return the number of trailing zeroes in N!.
Note:your solution should is in logarithmic time complexity. (easy)
Analysis: to find the number of the last 0 of the factorial of N, that is, to find the number of factors in the n! 5 (more than 2:5), the simple idea is to iterate over, for each number, divided by 5 to find the number of factor 5, but will time out.
Considering that a number n is more than 5 of the number of digits divisible by a few (N/5), and then consider divisible by 25, 125 is divisible by the number of numbers, get the following algorithm:
Code:
1 classSolution {2 Public:3 intTrailingzeroes (intN) {4 intsum =0;5 while(N >0) {6Sum + = (N/5);7N/=5;8 }9 returnsum;Ten } One};
258. Add Digits
Given a non-negative integer num
, repeatedly add all its digits until the result have only one digit.
For example:
Given num = 38
, the process is like: 3 + 8 = 11
, 1 + 1 = 2
. Since have only one 2
digit, return it.
Follow up:
Could do it without any loop/recursion in O (1) runtime?
Analysis:
Considering the
Ab% 9 = (9a + a + b)% 9 = (A + b)% 9;
ABC% 9 = (99a + 9 B + A + B + c)% 9 = (A + B + c)% 9;
So it is only a single digit position to use its MoD 9, considering that the number divisible by 9 should return 9 instead of 0, using the first minus repeated plus one way to deal with.
Code:
1 classSolution {2 Public:3 intAdddigits (intnum) {4 if(num = =0) {5 return 0;6 }7 return(Num-1) %9+1;8 }9};
268. Missing Number
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one and that's missing from the array.
For example,
Given nums = [0, 1, 3]
return 2
. (Medium)
Analysis:
Using the first sum (the first n and), and then the sum of the result and the array and subtract the method, the difference between the number of
Code:
1 classSolution {2 Public:3 intMissingnumber (vector<int>&nums) {4 intn =nums.size ();5 intSUM1 = n * (n +1) /2;6 intsum2 =0;7 for(inti =0; I < nums.size (); ++i) {8Sum2 + =Nums[i];9 }Ten returnSUM1-sum2; One } A};
LeetCode172 factorial Trailing Zeroes. LeetCode258 Add Digits. LeetCode268 Missing Number