1、判断一个数能不能被4开方
Power of Four
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example:
Given num = 16, return true. Given num = 5, return false.
Follow up:
Could you solve it without loops/recursion?
要是题目没有那局限制的话相信很多人一看到题目都会直接使用类方法(库函数)或者用循环/递归来解决这道题的吧。要是以前的我的话也会是这样做的,但是做这种类型的题目多了之后就会发现,自己不会老是喜欢用一种方法来解决一种类型的问题。
以下是我的想法:
public boolean isPowerOfFour(int num) {
if(num == 1) return true;
if((num % 10 == 4 || num % 10 == 6) && Integer.bitCount(num) == 1 && num > 0)
return true;
else
return false;
}
唉!我还是没能想到下面这种用二进制数操作来解决问题!)下面确实是一个更快,效率更高的代码:
public boolean isPowerOfFour(int num) {
return num > 0 && (num&(num-1)) == 0 && (num & 0x55555555) != 0;
}
解释一下上面为何还要与一下0x55555555,由于num & (num - 1)只保证了二进制位中只出现一个1,但是没有保证这个1会出现在奇数位,这个跟我用的bitCount()函数其实是一样的意思。有了最后num & 0x55555555就保证了这个这个1一定会出现奇数位上。
2、以集合式形式输出杨辉三角
Pascal’s Triangle
Given numRows, generate the first numRows of Pascal’s triangle.
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
//简洁的代码:
public List<List<Integer>> generate(int numRows){
List<List<Integer>> a = new ArrayList<List<Integer>>();
ArrayList<Integer> b = new ArrayList<>();
for(int i = 0; i < numRows; i++){
b.add(0,1);
for(int j = 1; j < b.size() - 1; j++){
b.set(j,b.get(j) + b.get(j+1));
}
a.add(new ArrayList(b));
}
return a;
}