需求:不使用局部变量和for循环或其它循环打印形如:2 4 8 16 16 8 4 2 这样的串
代码MainTest.java
package com.szp.study.javase.special; /** * 正向输出n的2的倍数,当大于m时始除以2并反向除于2输出,形如m=19,n=2;結果:2 4 8 16 16 8 4 2 * 在方法中不声明本地变量、不使用循环 * * @author zhipengs * */ public class MainTest { /** * @param args */ public static void main(String[] args) { int m = 19, n = 2; System.out.println("m=" + m + ",n=" + n); m = printMulti(m, n);// 调用递归乘 printDivide(m, n);// 调用递归除 m = 35; n = 4; System.out.println(" m=" + m + ",n=" + n); m = printMulti(m, n); printDivide(m, n); m = 40; n = 5; System.out.println(" m=" + m + ",n=" + n); m = printMulti(m, n); printDivide(m, n); m = 21; n = 1; System.out.println(" m=" + m + ",n=" + n); m = printMulti(m, n); printDivide(m, n); } /** * 递归乘 * @param m * @param n * @return int */ public static int printMulti(int m, int n) { if (n <= m) { System.out.print(n + " "); n = 2 * n; return printMulti(m, n); } return n; } /** * 递归除 * @param m * @param n * @return int */ public static int printDivide(int m, int n) { if (m > n) { m = m / 2; System.out.print(m + " "); return printDivide(m, n); }
return n; } }
测试结果:
m=19,n=2
2 4 8 16 16 8 4 2
m=35,n=4
4 8 16 32 32 16 8 4
m=40,n=5
5 10 20 40 40 20 10 5
m=21,n=1
1 2 4 8 16 16 8 4 2 1