面试题16
/** * 面试题16 求数值的整数次方 * 注意:非法输入的处理 * * @param base * @param exponent * @return */ public double power(double base, int exponent) throws Exception { if (base == 0.0 && exponent < 0) throw new Exception("base=0 and exponent<0"); //deal with invalid input if (exponent == 0) return 1;//exponent=0 int absExp = Math.abs(exponent);//get the abs of exponent double result = powerCore(base, absExp);//power if (exponent < 0) result = 1.0 / result;//deal with exponent<0 return result; } private double powerCore(double base, int absExp) { if(absExp==0) return 1; if(absExp==1)return base; double result = powerCore(base,absExp>>1); result *=result; if((absExp&0x01)!=0) result*=base; return result; } /* private double powerCore(double base, int absExp) { //使用动态规划的方法 double prevResult = base;//previous result int num = 1; while ((num = num<<1) <= absExp) { prevResult = prevResult * prevResult; } for(int i=0;i<absExp-(num>>1);i++){ prevResult *= base; } return prevResult; } */ public static void main(String[] args) { Solution solution = new Solution(); try { System.out.println(solution.power(2,7)); } catch (Exception e) { e.printStackTrace(); } }
面试题17
/** * 面试题17 打印1到最大的n位数 * 注意:大数问题,用数组来模拟大数的加减 * * @param n */ public void printMaxDigits(int n) { //invalid input if (n <= 0) return; int[] arr = new int[n + 1]; while (increatment(arr)) { StringBuilder str = new StringBuilder(n); int index = n; while (arr[index] == 0) index--; for (int i = index; i >= 1; i--) { str.append(arr[i]); } System.out.println(str); } } /** * 全排列的思想 * * @param n */ public void printMaxDigits2(int n) { if (n <= 0) return; int[] arr = new int[n]; //模仿大数的数组 for (int i = 0; i <= 9; i++) { arr[0] = i; printPermutation(arr, n, 0); } } /** * 打印数组arr,长度是n,已经确定i前索引对应的值的全排列 * @param arr * @param n * @param index */ private void printPermutation(int[] arr, int n, int index) { if(index == arr.length -1){ System.out.println(Arrays.toString(arr)); return; } for (int i = 0; i <= 9; i++) { arr[index+1] = i; printPermutation(arr, n, index+1); } } /** * 模拟大数的自增1 * * @param arr * @return 能自增时返回true,达到最大值时返回false */ private boolean increatment(int[] arr) { boolean suc = true; boolean flag = true; for (int i = 1; i <= arr.length - 1; i++) { if (flag) { //低位有进位 arr[i]++; if (arr[i] == 10) {//向高位进位 arr[i] = 0; flag = true; if (i == arr.length - 1)//最高位进位 suc = false; } else flag = false;//向高位无进位 } else break; } return suc; } public static void main(String[] args) { Solution solution = new Solution(); solution.printMaxDigits2(2); }