有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用Java8获取最有效的十进制数字

我正在尝试获取整数的最高有效小数位数,我的方法如下:

  1. I am trying to get the total number(count) of digits in the Integer(N);

  2. I am dividing the Integer(N) by the 1(....count times 0).

我已经完成了下面的代码,它工作得很好,如果可能的话,我只想用java-8实现它

int N = 456778889;
double expo = Math.log10(N);
int expNum = (int)Math.floor(expo)+1;  //gets the total digits in the Integer N

现在,因为我有N中的总位数,所以我可以将N除以1,然后再除以0的总数,为了实现这个1,然后是X个零,我的逻辑如下:

    StringBuilder sb = new StringBuilder("1");
    sb.setLength(expNum);
    String f = sb.toString().replaceAll("[^0-9]","0"); // It makes the 1 followed by X amount of zero that i require to get my MSB
    int mostSigNum = N/(Integer.valueOf(f));
    System.out.println(mostSigNum);

我知道我的方法有点不同,因为我主要使用log和其他数学函数,但我真的想用不同的方法

任何Java8stream类型中有帮助的方法都将不胜感激


共 (4) 个答案

  1. # 1 楼答案

    根据我的理解,你的解决方案的第一部分是最简单的,并且是有效的,而不是除以10,直到没有余数为止

    int N = 456778889;
    double expo = Math.log10(N);
    int expNum = (int)Math.floor(expo);
    

    现在,考虑到每个流,我们可以执行以下操作来生成除数,除数为1,后跟X个零的量,使用该值时可以得到MSB(最高有效位):

        String c = IntStream.range(0,expNum).mapToObj(e->"0").collect(Collectors.joining(""));
        String t = "1".concat(c);
        int maxi = N/Integer.parseInt(t);
        System.out.println(maxi);
    
  2. # 2 楼答案

    一个简单的解决方案是反复除以10,直到剩下一位数:

    int number = 456778889;
    int result = IntStream.iterate(number, i -> i / 10) // divide by 10
                          .filter(i -> i < 10)          // filter out if multiple digits
                          .findFirst().getAsInt();      // get the first value
    

    以下是不使用流的相同解决方案:

    int number = 456778889;
    int result;
    for (result = number; result >= 10; result /= 10);
    
  3. # 3 楼答案

    当你继续使用log10的舍入值时,你也应该一直使用Math.pow(10, …)来进入另一个方向,而不是突然切换到String操作

    int maxi = (int)(N/Math.pow(10, Math.floor(Math.log10(N))));
    

    如前所述,在评论中,当您使用String操作时,Integer.toString(N).substring(0,1)会得到一个完整的解决方案。或者,要获取int值:

    int maxi = Character.digit(String.valueOf(N).charAt(0), 10);
    
  4. # 4 楼答案

    在java8中,它非常简单

    public int maxi(int n) {
        return String.valueOf(n)
                .chars()
                .map(i -> i - '0')
                .max()
                .orElse(0);
    }
    
    @Test
    public void testMaxi() {
        assertEquals(1, maxi(1000));
        assertEquals(7, maxi(7654));
        assertEquals(9, maxi(456778889));
    }