java - 数字的乘积

标签 java

public class ProductOfDigits {
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter an integer: ");
    int n = input.nextInt();
    int x = Math.abs(n);
    int product = 1; 

        if (x >=0 && x<=9) {
            System.out.println(x);
        }
        else  {         
        product = product * (x % 10); 
        x = x/10;
        System.out.println(product);
        }

当输入为负数时,乘积是第一个数字和最后一个数字之间的结果。谁能解释一下吗?我尝试过使用 Math.abs() 来获取绝对值,但这是不可能的,而且现在简直要了我的命。

最佳答案

按如下方式进行:

import java.util.Scanner;

public class ProductOfDigits {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        int n = input.nextInt();
        int x = Math.abs(n);
        int ç = 1;
        int product = 1;
        if (x == 0) {
            product = 0;
        } else {
            while (x > 0) {
                product *= x % 10;
                x /= 10;
            }
        }
        System.out.println(product);
    }
}

示例运行 1:

Enter an integer: -256
60

示例运行 2:

Enter an integer: 0
0

示例运行 3:

Enter an integer: 9
9

示例运行 4:

Enter an integer: 256
60

递归版本:

import java.util.Scanner;

public class ProductOfDigits {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        int n = input.nextInt();
        System.out.println(productOfDigits(n));
    }

    static int productOfDigits(int n) {
        n = Math.abs(n);
        if (n > 0 && n < 10) {
            return n;
        }
        if (n == 0) {
            return 0;
        }
        return (n % 10) * productOfDigits(n / 10);
    }
}

关于java - 数字的乘积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60129476/

相关文章:

java - 目录递归 - 如果第一个文件遇到的是目录会发生什么

java - 从pdf中提取粗体字

java - 组合框 Java 的文档未更新

java - GSON : java. lang.IllegalStateException:应为 BEGIN_OBJECT 但为 STRING

java - 提取 Try/Catch block - Microsoft 约定/标准

java - 由: org. springframework.data.redis.serializer.SerializationException引起 : Cannot deserialize; nested exception is org. springframework.core.seriali

java - 为什么 Reflections.getFieldsAnnotatedWith() 不返回任何字段?

java - 有没有办法通过 checkstyle 或 findbugs 限制某些 java 导入

java - 如何将 List<Map<String, Object>> 转换为 List<Map<String, String>>

c# - 链表 <T> (2.0) : removing items iteratively