使用Java8获取最有效的十进制数字
我正在尝试获取整数的最高有效小数位数,我的方法如下:
I am trying to get the total number(count) of digits in the Integer(N);
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和其他数学函数,但我真的想用不同的方法
任何Java8和stream类型中有帮助的方法都将不胜感激
# 1 楼答案
根据我的理解,你的解决方案的第一部分是最简单的,并且是有效的,而不是除以10,直到没有余数为止
现在,考虑到每个流,我们可以执行以下操作来生成除数,除数为1,后跟X个零的量,使用该值时可以得到MSB(最高有效位):
# 2 楼答案
一个简单的解决方案是反复除以10,直到剩下一位数:
以下是不使用流的相同解决方案:
# 3 楼答案
当你继续使用
log10
的舍入值时,你也应该一直使用Math.pow(10, …)
来进入另一个方向,而不是突然切换到String
操作如前所述,在评论中,当您使用
String
操作时,Integer.toString(N).substring(0,1)
会得到一个完整的解决方案。或者,要获取int
值:# 4 楼答案
在java8中,它非常简单