微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

最少有价值的数字

如何解决最少有价值的数字

这是我的代码,我不知道为什么12后的答案不正确。 首先,我计算输入数字的阶乘,然后必须显示最不有价值的数字。

   
public class q3411 {
    public static int leastValuableDigit(int n) {
        for(int i = 0; i < String.valueOf(n).length(); i++) {
            int x = (int) Math.floor((n % Math.pow(10,i + 1)) / Math.pow(10,i));
            if(x != 0) return x;
        }

        return -1;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(system.in);
        int n = sc.nextInt();

        int fon = 1;

        for(int i = 1; i <= n; i++) fon *= i;

        System.out.println((leastValuableDigit(fon)));
    }
}

解决方法

首先,我更改了查找更多数字的阶乘的算法。 通过从阶乘中删除全0并取其最后一个字节,可以更改查找所需数字的算法。

    import java.math.BigInteger;
    import java.util.Scanner;
    
    public class Main {
        public static byte leastValuableDigit(BigInteger n) {
            String num = String.valueOf(n).replaceAll("0","");
            return Byte.parseByte(String.valueOf(num.charAt(num.length() - 1)));
        }
        
        public static BigInteger getFactorial(int f) {
            if (f <= 1) {
                return BigInteger.valueOf(1);
            }
            else {
                return BigInteger.valueOf(f).multiply(getFactorial(f - 1));
            }
        }
        
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
    
            BigInteger fon = getFactorial(n);
    
            System.out.println((leastValuableDigit(fon)));
        }
    }

您的算法不正确,导致您执行了许多不必要的计算和四舍五入

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。