P1:斐波拉契数列
递归函数/迭代三变量/迭代数组
P2:greatest-common-divisor最大公因数
(辗转相除法)
public class GreatestCommonDivisor {
//非递归
public static int gcd(int a, int b) { // a>b int m = Math.max(a,b); int n = Math.min(a,b); a = m;b = n; while (a%b!=0){ m = a%b; a = b; b = m; } return b; }
//递归
public static int gcdRecursive(int a,int b){ int m = Math.max(a,b); int n = Math.min(a,b); if(m%n==0){ return n; } else return gcdRecursive(n,m%n); } }
P3:海明距离
String str = Integer.toBinaryString(x^y);
String ~= Integer.toBinaryString(int);
x^y:异或运算
按位运算:& | ~ ^
<< | 左移运算符,将运算符左边的对象向左移动运算符右边指定的位数(在低位补0) | |
>> | "有符号"右移运算 符,将运算符左边的对象向右移动运算符右边指定的位数。使用符号扩展机制,也就是说,如果值为正,则在高位补0,如果值为负,则在高位补1. | |
>>> | "无符号"右移运算 符,将运算符左边的对象向右移动运算符右边指定的位数。采用0扩展机制,也就是说,无论值的正负,都在高位补0. |
P4:快乐数
(对于一个正整数,每一次将该数替换为他每个位置上的数字的平方和,然后重复这个过程直到这个数可以变为1)
Math.pow(底数,指数);
P5:实现 Math.abs
public static double abs(double d){ // // if (d>0) // return d; // else // return -d; return d>0? d:(-d); }判断语句?(when true):(when false)