Hnorth
Hnorth

Reputation: 55

Java Method: Integer contains 1

I am trying to create a method that will return true if the inputted integer has a one in it, and false if it does not. The method works correctly when the inputted number doesn't have a one or ends in a one. But if the one is not the last digit in the int, it incorrectly returns false. Any ideas whats wrong? Here is my script:

public static boolean hasOne(int n) {
    boolean retval = false;

    if (n % 10 == 1) {
        retval = true;
    } else {
        dropLastDig(n);
    }
    return retval;
}

public static void dropLastDig(int input) {
    int newNum = input/10;

    if (newNum > 0) {
        hasOne(newNum);
    }
}

1000 should return true

211 should return true

1 should return true

3 should return false

234 should return false

Upvotes: 2

Views: 509

Answers (3)

Beri
Beri

Reputation: 11620

You can use recursive function, it's faster:

public static boolean hasOne(int n) {
  if(n<0) return hasOne(-n); // check for negatives
  if(n==0) return false; // exit condition

  if (n % 10 == 1) {
    return true;
  } 
  return hasOne(n/10);
}

Or cast it to String, and then check:

String.valueOf(n).contains("1");

Upvotes: 2

ThomasEdwin
ThomasEdwin

Reputation: 2145

try String.valueOf(n).contains("1")

Upvotes: 1

johnII
johnII

Reputation: 1433

Just use String.valueOf instead

return String.valueOf(x).contains("1");

Upvotes: 2

Related Questions