简体   繁体   English

如何在不使用控制语句或循环的情况下将整数中的所有数字(在000和1000之间)相乘?

[英]How can I multiply all the digits in an integer (between 000 & 1000 exclusive) without using control statements or loops?

I'm trying to write a program that can multiply all the digits of a number from 0 to 1000 exclusive using only math expressions in Java. 我正在尝试编写一个程序,它可以将数字的所有数字从0添加到1000,仅使用Java中的数学表达式。 My program works fine as long as the user types in a 3-digit number, but results in 0 if they type in anything less than 100. 只要用户输入一个3位数字,我的程序就可以正常工作,但如果输入的数字少于100,则结果为0。

I have tried getting the last digit of the input with '%10' and removing the last digit with '/10' but without a control statement to detect if the input has been reduced to zero, the program ends up multiplying by 0 when a 2-digit number has been reduced to zero, giving an incorrect result. 我已经尝试用'%10'获取输入的最后一位数并用'/ 10'删除最后一位但没有控制语句来检测输入是否已减少到零,程序最终乘以0乘以0 2位数字已减少为零,结果不正确。

public class MultiplyDigits {
    public static void main(String[] args){
        java.util.Scanner input = new java.util.Scanner(System.in);
        System.out.print("Enter a number between 0 and 1000: ");
        int number = input.nextInt();
        int product = 1;
        product*=number%10;
        number/=10;
        product*=number%10;
        number/=10;
        product*=number%10;
        System.out.println(product);
    }
}

An input of 55 should result in 25, but my program does 5 x 5 x 0 = 0 输入55应该导致25,但我的程序执行5 x 5 x 0 = 0

An input of 999 results in 729, which is correct. 输入999会产生729,这是正确的。 9 x 9 x 9 = 729 9 x 9 x 9 = 729

Some more clarification, this is a problem out of the 2nd chapter of a textbook for complete novices. 更进一步的澄清,这是完整新手教科书第2章中的一个问题。 The author has not covered selection statements, loops, writing our own methods or classes, or anything more advanced than elementary programming, so the implication is that this is doable without those. 作者没有涵盖选择语句,循环,编写我们自己的方法或类,或者比基本编程更先进的东西,所以暗示如果没有这些,这是可行的。 The book has covered invoking methods in classes built into Java, although the author has only mentioned methods in the Math and System classes. 本书已经介绍了在Java中构建的类中的调用方法,尽管作者只提到了Math和System类中的方法。 For example, Math.max(), Math.min(), Math.pow(), System.currentTimeMillis(); 例如,Math.max(),Math.min(),Math.pow(),System.currentTimeMillis();

What about this variant. 这个变种怎么样? To find the first number, you can decrease, first of all, the entered number by 100 and add 1 to avoid 0 during multipication. 要查找第一个数字,首先可以减少输入的数字100,并在乘法时加1以避免0。 And , as recomended NVioli, the second number should be the same updated to have a possibility to enter number lower then 10. Thus, the final variant is: 并且,作为推荐的NVioli,第二个数字应该相同更新,以便有可能输入低于10的数字。因此,最终的变体是:

int number = input.nextInt();

    int t1 = 1 + (number-100) / 100;
    int t2 = (1 + (number-10) / 10) % 10; \\By NVioli
    int t3 = number % 10;

    int  product = t1 * t2 * t3;

    System.out.println(product);

The first part is to extract the essential code into a separate Java method. 第一部分是将基本代码提取到单独的Java方法中。 I'm calling it dprod , which is short for "digit product". 我称之为dprod ,这是“数字产品”的缩写。

static int dprod(int x) {
    int hun = x / 100 % 10;
    int ten = x / 10 % 10;
    int one = x / 1 % 10;

    return hun * ten * one;
}

The above code is the naive version that only works for numbers >= 100 . 上面的代码是天真的版本,仅适用于>= 100数字。

To treat numbers less than 100 as expected, you need to replace the hun or ten with 1 if it is 0. 要按预期处理小于100的数字,如果为0,则需要将hunten替换为1。

static int dprod(int x) {
    int hun = x < 100 ? 1 : x / 100 % 10;
    int ten = x < 10 ? 1 : x / 10 % 10;
    int one = x / 1 % 10;

    return hun * ten * one;
}

The ?: operator is called a conditional operator, therefore it is probably not allowed under your rules. ?:运算符称为条件运算符,因此根据您的规则可能不允许。 There is a possible workaround by using the ?: operator without writing it explicitly, by using the Math.max function. 通过使用Math.max函数,可以使用?:运算符而无需显式编写它。

static int dprod(int x) {
    int hun = Math.max(100, x) / 100 % 10;
    int ten = Math.max(10, x) / 10 % 10;
    int one = x / 1 % 10;

    return hun * ten * one;
}

The Math.max function uses the ?: operator internally, therefore it might be forbidden, too. Math.max函数在内部使用?:运算符,因此也可能被禁止。 This is subject to discussion though, since it depends on the exact wording of the rules and their intention. 这可以讨论,因为它取决于规则的确切措辞及其意图。

If Math.max is forbidden, it is possible to implement it entirely without branches or conditions, see this C++ question , which can be translated to Java by replacing int32 with int and by replacing inline with static . 如果Math.max是禁止的,所以能够完全实现它没有分支或条件,参见该C ++问题 ,其可以通过更换被翻译成Java int32int和通过更换inlinestatic

The complete code, including automatic tests, is: 完整的代码,包括自动测试,是:

package de.roland_illig.so;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;

public class DprodTest {

    static int dprod(int x) {
        int hun = Math.max(x, 100) / 100 % 10;
        int ten = Math.max(x, 10) / 10 % 10;
        int one = x / 1 % 10;

        return hun * ten * one;
    }

    @Test
    public void testDprod() {
        assertThat(dprod(999)).isEqualTo(729);
        assertThat(dprod(123)).isEqualTo(6);
        assertThat(dprod(99)).isEqualTo(81);
        assertThat(dprod(9)).isEqualTo(9);
    }
}

You could just initialize the program with a length 1000 array, initialize it with the value of each number, and then your real problem simplifies to: 您可以使用长度为1000的数组初始化程序,使用每个数字的值初始化它,然后您的真正问题简化为:

System.out.println(calculatedArray[number]);

Your initialization could even take advantage of the fact that a leading 0 doesn't matter according to your rules (55 and 155 are the same result.) 您的初始化甚至可以利用前导0根据您的规则无关紧要的事实(55和155是相同的结果。)

calculatedArray[55] = calculcate(155);

there are some ways which can help you but all of them has a simple loop or if: 有一些方法可以帮助你,但所有这些方法都有一个简单的循环或如果:

  1. You can use digits = Logarithm of your number(10 base) and then you have number of digits, then you can use a loop to calculate the result. 您可以使用digits = Logarithm of your number(10 base)然后您有数字位数,然后您可以使用循环来计算结果。 your loop will be repeated digit times so no matter how many digits your number has, it will always work. 你的循环将重复digit时间,所以无论你的数字有多少位数,它都会一直有效。

  2. You can check if your number is less than 100 and then just add 100 to that, then calculate the result, because of 1 * digit1 * digit2 there will be no error. 您可以检查您的数字是否小于100,然后只需添加100 ,然后计算结果,因为1 * digit1 * digit2将没有错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Java中将两个整数之间的所有数字相乘而不使用循环 - Multiply all number between two integer in java without using loop 如何将int的所有数字相乘而不将其转换为字符串,然后将charAt函数与for循环一起使用? - How to multiply all the digits of an int without converting them to string and then using the charAt function with a for loop? 仅使用循环和Java中的if语句查找1-1000之间的理想数 - Finding perfect numbers between 1-1000 only using loops and if statements in Java 如何生成整数数字的平方 - How can I generate the squares of the digits of an integer 如何使用for循环交换Java中数字的第一个和最后一个数字? - How can I swap the first and last digits of a number in Java using for for-loops? 如何在不使用字符串的情况下确定输入的整数是否包含某些数字 - How to determine if an inputted integer contains certain digits without using strings 如何在不使用任何循环的情况下计数? - How can I count up without using any loops? 如何通过传递一个整数来实现一个返回字符串的方法,而不需要很多if语句? - How can I implement a method which returns a string by passing an integer, without having lot of if statements? 如何判断整数只有2位数字? - How can I tell that an integer is only 2 digits long? 如何使用Integer.toBinaryString设置Java中的位数? - How with Integer.toBinaryString can I set the amount of digits in java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM