不使用局部变量和for循环或其它循环打印出如m=19,n=2結果为2 4 8 16 16 8 4 2形式的串
需求:不使用局部变量和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("\nm=" + m + ",n=" + n); m = printMulti(m, n); printDivide(m, n); m = 40; n = 5; System.out.println("\nm=" + m + ",n=" + n); m = printMulti(m, n); printDivide(m, n); m = 21; n = 1; System.out.println("\nm=" + 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
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。