Question

Is there something I can use to see if a number starts with the same digit as another? Ex. 5643 and 5377 both start with five.

Is there a way to do this with numbers or do they have to be strings? (startsWith?)

Was it helpful?

Solution

Ich n1 and n2 are your numbers:

return (n1.toString().charAt(0) == n2.toString().charAt(0));

You will have to use Integer not int, since int has no .toString() method.

If n1 is an int you could use new Integer(n1).toString().

Or even better (suggested by Bombe):

String.valueOf(n1).charAt(0) == String.valueOf(n2).charAt(0)

OTHER TIPS

Recurse dividing by ten until the whole division is less than ten, then that number is the first one and you can compare numbers.

You could calculate the first digit:

public int getFirstDigit(int number) {
    while (number >= 10) {
        number /= 10;
    }
    return number;
}

(This will only work for positive numbers.)

But then again you could just compare the first character of the String representations. The string comparison may be slower but as your problem is “getting the first character of the string representation” it might just be the appropriate solution. :)

The most straight-forward approach (allowing for different length values) would probably be just as you said, convert them both to Strings.

int x = 5643;
int y = 5377;
String sx, sy;

sx = "" + x;        // Converts int 5643 to String "5643"
sy = "" + y;

boolean match = (sx.charAt(0) == sy.charAt(0));
  public static byte firstDigit(int number) {
    while (true) {
      int temp = number / 10;

      if (temp == 0) {
        return (byte) Math.abs(number);
      }

      number = temp;
    }

(int)(a / 10 ** (int)Math.log10(a))

Probably less efficient than the string solution, but no looping and it keeps us in the "Numeric" realm.

(Always remember that when you are talking about the number of digits in a number, log10 is your friend)

Also won't work for negative numbers-take an absolute value of a first.

For ints, int n1 and int n2;

return ("" + n1).charAt(0) == ("" + n2).charAt(0);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top