/* * Recursive Multiply: Write a recursive function to multiply two positive integers without using the * operator * (or / operator). You can use addition, subtraction, and bit shifting, but you should minimize the number of those * operations. * * 方法:找到两个数中小的一个 每次除二 如果单数 则把除二加一传入递归 最后合并; * */ public class Main { public static void main(String[] args) { System.out.println("Hello World!"); int a = 23, b = 13; if(a < b) { System.out.println(multi(a, b, new int[a + 1])); } else { System.out.println(multi(b, a, new int[a + 1])); } } public static int multi(int small, int big, int[] memo) { if(small == 0) return 0; if(small == 1) return big; if(memo[small] != 0) return memo[small]; int side1 = multi(small >> 1, big, memo); int side2 = side1; if(small % 2 == 1) { side2 = multi((small >> 1) + 1, big, memo); } memo[small] = side1 + side2; return memo[small]; } }
Recursive Multiply java 走地牙 CTCI 8.5
最新推荐文章于 2023-04-24 08:56:42 发布