Trailing Zeros
Write an algorithm which computes the number of trailing zeros in n factorial.
思路:1*2*3*4*5*6*7*8*9*10
前5个数中有一个2一个5,相乘有一个0,后5个数中有一个10,也有一个0,因此,每5个数中会有一个0
class Solution {
/*
* param n: As desciption
* return: An integer, denote the number of trailing zeros in n!
*/
public long trailingZeros(long n) {
long sum=0;
while(n!=0){
sum+=n/5;
n/=5;
}
return sum;
}
}
Flip Bits
Determine the number of bits required to flip if you want to convert integer nto integer m.
Both n and m are 32-bit integers.
Given n = 31
(11111), m = 14
(01110), return 2
.
思路:1. 先异或运算拿到结果,结果里的1的个数就是不一样的个数
异或运算:两位不同,亦或结果为1,如图,两个1不同
2. 再用按位与数出来上面得到的不同的结果
按位与:只有两位同时为1时,结果才为1,如图
3. 然后无符号移位到下一位
java中有三种移位运算, 例如32bits
<<:左移运算符,num<<1,相当于num乘以2
1的表示: 0000 0000 0000 0000 0000 0000 0000 0001,左移一位:0000 0000 0000 0000 0000 0000 0000 0010
>>:右移运算符,num>>1,相当于num除以2
-1的表示:(最前面的1是符号位)1000 0000 0000 0000 0000 0000 0000 0001,右移一位:1100 0000 0000 0000 0000 0000 0000 0000
>>>:无符号右移,忽略符号位,空位都以0补齐
-1的表示:1000 0000 0000 0000 0000 0000 0000 0001,右移一位:0100 0000 0000 0000 0000 0000 0000 0000
class Solution {
/**
*@param a, b: Two integer
*return: An integer
*/
public static int bitSwapRequired(int a, int b) {
int c= a ^ b; //异或运算
int totalBit=0;
while(c!=0){
int bit =c & 1; //按位与
totalBit+=bit;
c=c>>>1; //无符号右移
}
return totalBit;
}
};
Fast Power
Calculate the an % b where a, b and n are all 32bit integers.
For 231 % 3 = 2
For 1001000 % 1000 = 0
class Solution {
/*
* @param a, b, n: 32bit integers
* @return: An integer
*/
public int fastPower(int a, int b, int n) {
if(n==0) {
return 1%b;
}
long v=fastPower(a, b, n/2); //一直给n除以2直到n=0
v=(v*v)%b;
if(n%2==1){ //如果原n不能被2整除,还有一个a要处理
v=(v*a)%b;
}
return (int)v;
}
}
Unique Binary Search Tree
Given n, how many structurally unique BSTs (binary search trees) that store values 1...n?
Given n = 3, there are a total of 5 unique BST's.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
public class Solution {
/**
* @paramn n: An integer
* @return: An integer
*/
public int numTrees(int n) {
int[] count=new int[n+2];
count[0]=1;
count[1]=1;
for(int i=2;i<=n;i++){
for(int j=0;j<i;j++){
count[i]+=count[j]*count[i-j-1];
}
}
return count[n];
}
}