递归方法-Java [英] Recursive method - Java

查看:71
本文介绍了递归方法-Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

附加信息:

芯片不支持乘法,仅支持加法.我应该通过创建执行乘法的递归方法mult()来解决此问题. 通过将x加到自身y次获得x和y的乘积.它的参数是x和y及其返回 值是x和y的乘积.然后,我应该将方法和main()编写为 叫它.

Chip doesn't support multiplication, only addition. I should work around this problem by creating a recursive method, mult(), that performs multiplication of x and y by adding x to itself y times. Its arguments are x and y and its return value is the product of x and y. I should then write the method and a main() to call it.

这是纯粹的逻辑思维,但是每次尝试思考该怎么做时我都会迷路.

It's pure logical thinking, but I get lost every time I try to think what to do.

我被数学困住了. 我所拥有的东西不起作用,我知道数学是错误的,但是我对此并不擅长:

I am stuck at the math part.. What I have, that doesn't work and I know the math is wrong, but I am not good at this:

public static void mult(int x, int y) {
    x = 0;
    y = 0;
    if (y > 0) {
        for (int i = 0; i < y; i++) {
            x = x * (x * y);
            return mult(x, y);
        }
    }
}

推荐答案

public static int mult(int x, int y) {
        if (y == 0) {
            return 0;
        }
        if (y > 0) {
            return x + mult(x, y - 1);
        } else {
            return -x + mult(x, y + 1);
        }
    }

这是解决方案

这篇关于递归方法-Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆