3

Possible Duplicate:
Return first digit of an integer

In my java program, I store a number in an array.

p1Wins[0] = 123;

How would I check the first digit of p1Wins[0]? Or the second or third? I just need to be able to find the value of any specific digit.

Thanks!

Community
  • 1
  • 1
dualCore
  • 609
  • 4
  • 9
  • 13
  • Convert it to a string and use `charAt`? What have you tried so far? – Dave Newton Feb 12 '12 at 23:30
  • Out of curiosity: what's the use case of this? Why do you need to get that digit? There might be better ways to achieve your ultimate goal, so you might want to elaborate a bit on that. – Thomas Feb 12 '12 at 23:36

4 Answers4

25

Modular arithmetic can be used to accomplish what you want. For example, if you divide 123 by 10, and take the remainder, you'd get the first digit 3. If you do integer division of 123 by 100 and then divide the result by 10, you'd get the second digit 2. More generally, the n-th digit of a number can be obtained by the formula (number / base^(n-1)) % base:

public int getNthDigit(int number, int base, int n) {    
  return (int) ((number / Math.pow(base, n - 1)) % base);
}

System.out.println(getNthDigit(123, 10, 1));  // 3
System.out.println(getNthDigit(123, 10, 2));  // 2
System.out.println(getNthDigit(123, 10, 3));  // 1
João Silva
  • 89,303
  • 29
  • 152
  • 158
0

Tried

String.valueOf(Math.abs((long)x)).charAt(0)

?

TBH
  • 451
  • 2
  • 9
0

You will have to do some math magic to get the nth digit of an arbitrary number, basically using division and modulo 10 if you want it to be a number. Otherwise string ops will work.

int nth ( int number, int index ) {
    return ((int)number / java.lang.Math.pow(10, index)) % 10;
}

char nth ( int number, int index ) {
    return String.valueOf(java.lang.Math.abs(number)).charAt(index);
}

Mind you the modulo method will take form the right side and the string will take from the left;

zellio
  • 31,308
  • 1
  • 42
  • 61
  • I don't think you want to use exclusive-or (`^`) there. – Greg Hewgill Feb 12 '12 at 23:31
  • @GregHewgill - haha yeah, sorry I prototyped the function in psudeo code and then suddenly couldn't remember the `Math.pow` function so I had to go look it up. – zellio Feb 12 '12 at 23:35
0
Integer(plWins[0]).toString().charAt(0)

You're turning your number into a string and then performing a charAt. 0 can be replaced with any other character, as well. It's not too elegant, but I believe Java does not provide any more straightforward a method. You may also choose to cast it to an int if char is not your preferred type.

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
hexparrot
  • 3,399
  • 1
  • 24
  • 33