1. Factorial Trailing Zeroes 算是个小的智力题
public class Solution {
public int trailingZeroes(int n) {
if (n < 0)
return -1;
int count = 0;
for (long i = 5; n / i >= 1; i *= 5) {
count += n / i;
}
return count;
}
}
2. Rotate Array 移动array元素特定步(三步反转法)
public class Solution {
public void reverse(int[] arr, int left, int right){
if(arr == null || arr.length == 1)
return;
while(left < right){
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
public void rotate(int[] nums, int k) {
k = k % nums.length;
if (nums == null || k < 0) {
throw new IllegalArgumentException("Illegal argument!");
}
//length of first part
int a = nums.length - k;
reverse(nums, 0, a-1);
reverse(nums, a, nums.length-1);
reverse(nums, 0, nums.length-1);
}
}
3. Reverse Bits
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
for (int i = 0; i < 16; i++) {
n = swapBits(n, i, 32 - i - 1);
}
return n;
}
public int swapBits(int n, int i, int j) {
int a = (n >> i) & 1;
int b = (n >> j) & 1;
if ((a ^ b) != 0) {
return n ^= (1 << i) | (1 << j);
}
return n;
}
}