另一种在不使用“*”的情况下将两个数相乘的方法。操作者 [英] Another method to multiply two numbers without using the "*" operator

查看:192
本文介绍了另一种在不使用“*”的情况下将两个数相乘的方法。操作者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我昨天接受了一次有趣的采访,面试官问我一个经典问题:如何在不使用 * 运算符的情况下在Java中乘以两个数字。老实说,我不知道这是采访带来的压力,但我无法提出任何解决方案。

I had an interesting interview yesterday where the interviewer asked me a classic question: How can we multiply two numbers in Java without using the * operator. Honestly, I don't know if it's the stress that comes with interviews, but I wasn't able to come up with any solution.

面试后,我去了回家后通过SO微风轻拂。到目前为止,这里是我找到的:

After the interview, I went home and breezed through SO for answers. So far, here are the ones I have found:

第一种方法:使用For循环

// Using For loop
public static int multiplierLoop(int a, int b) {
    int resultat = 0;
    for (int i = 0; i < a; i++) {
        resultat += b;
    }

    return resultat;
}

第二种方法:使用递归

// using Recursion
public static int multiplier(int a, int b) {

    if ((a == 0) || (b == 0))
        return 0;
    else
        return (a + multiplier(a, b - 1));

}

第三种方法:使用Log10

**// Using Math.Log10
public static double multiplierLog(int a, int b) {
    return Math.pow(10, (Math.log10(a) + Math.log10(b)));
}**

所以现在我有两个问题要问你:

So now I have two questions for you:


  1. 我还缺少另一种方法吗?

  2. 我无法得出答案的事实证明我的逻辑推理不够强大,无法提出解决方案,而且我没有切出 成为一名程序员?因为说实话,问题似乎并不那么困难,我很确定大多数程序员都会轻松快速地找到答案。


推荐答案

我不知道这是否必须是一个严格的编程问题。但在数学中:

I don't know whether that has to be a strictly "programming question". But in Maths:

x * y = x / (1 / y) #divide by inverse

所以:

方法1

public static double multiplier(double a, double b) {

    // return a / (1 / b);

    // the above may be too rough
    // Java doesn't know that "(a / (b / 0)) == 0"
    // a special case for zero should probably be added:

    return 0 == b ? 0 : a / (1 / b);
}

方法2 (更多编程/ API 解决方案:

Method 2 (a more "programming/API" solution):

使用大小数,大整数:

new BigDecimal("3").multiply(new BigDecimal("9"))

有可能还有几种方法。

这篇关于另一种在不使用“*”的情况下将两个数相乘的方法。操作者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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