lintcode做题总结, Sept 16

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;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值