简体   繁体   English

Java在int中找到第二位数字

[英]Java find second-leading digit in int

I am working on a Java problem in which I need to check if the second-leading digit of an int (ex: the '2' in 123, or the '8' in 58347) of any size is a particular digit (such as a '2' or a '5'), and then assign true to a Boolean, if it is that digit.我正在处理一个 Java 问题,我需要检查任何大小的 int 的第二个前导数字(例如:123 中的“2”或 58347 中的“8”)是否是特定数字(例如'2' 或 '5'),然后将 true 分配给布尔值,如果它是那个数字。 I am trying to do the modulo/divisor method, but I am not able to extract the second-leading digit if the number is large.我正在尝试使用模/除数方法,但如果数字很大,我将无法提取第二位数字。

I searched Stack Overflow, and found a very similar question.我搜索了 Stack Overflow,发现了一个非常相似的问题。 However, the solution for that question works if the number is hard-coded as being two digits.但是,如果数字被硬编码为两位数,则该问题的解决方案有效。 I know there is a way by converting int to String, and I tried that method successfully, but I need to use int/modulo/division method.我知道有一种方法可以将 int 转换为 String,并且我成功地尝试了该方法,但是我需要使用 int/modulo/division 方法。 I tried doing (n%100)/10;我试着做 (n%100)/10; but it got me second-to-last digit (ex: the '7' in 4562374), not second-after-first digit.但它让我得到倒数第二个数字(例如:4562374 中的“7”),而不是第一个数字之后的第二个数字。

// n is a number such as 123, or 25, or 52856.
while (n > 0) { 
int i=((n%10)/10);
if( (i==2)||(i==3) || (i==5)|| (i==7) )
{ secondDigit=true; }
else { secondDigit= false; } }
System.out.println(secondDigit);

Just keep dividing by 10 until the number is < 100 then do modulo 10, example:继续除以 10 直到数字 < 100 然后做模 10,例如:

class Main {
  public static void main(String[] args) {
    int n = 58347;
    while (n >= 100) {
      n /= 10;
    }
    System.out.println(n % 10); // prints 8
  }
}

Not certain about the efficiency of this method, however its easy to read.不确定此方法的效率,但它易于阅读。

Integer.parseInt(String.valueOf(Math.abs(initial_value)).charAt(1)+"")

However, you have to ensure that the number has more than 1 digit.但是,您必须确保该号码超过 1 位。

Instead of repeatedly dividing the number you have until it's small enough for you to handle, how about finding out how big the number is so you only need to do a single division?与其反复将您拥有的数字除以直到它小到足以让您处理,不如找出这个数字有多大,这样您只需要进行一次除法?

What I mean is that you should consider using logarithms to find out the magnitude of your number.我的意思是你应该考虑使用对数来找出你的数字的大小。 Finding the base 10 logarithm of your number gets you its magnitude.找到以 10 为底的数字的对数可以得到它的大小。 For 100 the log_10 is 2, so you can do the following:对于 100,log_10 为 2,因此您可以执行以下操作:

long magnitude = Math.log10(number);
long divisor = Math.pow(10, magnitude - 1);
long smallNumber = number / divisor;
int digit = smallNumber % 10;

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM