1.最常见的方式,使用位移替代乘除法
举例:乘以2,相当于左移一位,除以2相当于右移一位。
n = n << 1; // 乘以2
n = n >> 1; // 除以2
一般要求被乘数和被除数是2的N次方,那么怎么判断是否2的N次方呢?
/* Method to check if x is power of 2*/ static boolean isPowerOfTwo (int x) { /* First x in the below expression is for the case when x is 0 */ return x!=0 && ((x&(x-1)) == 0);
或者统计x的二进制数据中1的个数是不是仅仅有一个(排除0,1)
public static void main(String[] args) { String bis="59"; BigInteger bi=new BigInteger(bis,10); System.out.println(bi.bitCount()); }
2.判断一个数是否素数?BigInteger内置了实现。
BigInteger.valueOf(1235).isProbablePrime(1)
3排序算法
Arrays.sort() 对数据进行排序.
Collections.sort() 对集合进行排序.
4.搜索算法
Arrays.binarySearch()(SET 1 | SET2) 针对一个排序好的数组进行二分法查找
Collections.binarySearch() 针对使用comparator排序好的集合进行二分法查找
5.拷贝算法
Arrays.copyOf() 和copyOfRange() 拷贝特定的数组.
Collections.copy() 拷贝特定的集合.