Java > AP-1 > hasOne (CodingBat Solution)

Problem:

Given a positive int n, return true if it contains a 1 digit. Note: use % to get the rightmost digit, and / to discard the rightmost digit.

hasOne(10) → true
hasOne(22) → false
hasOne(220) → false


Solution:

public boolean hasOne(int n) 
{
  while(n%10!=0||n==10)
  {
    if(n%10 == 1)
      return true;
    else
      n/=10;  
  }  
  
  return false;  
}


15 comments :

  1. I realize your solution was probably preferable, but I found another way:

    public boolean hasOne(int n) {
    String nString = n + "";
    return nString.contains("1");
    }

    ReplyDelete
  2. If you put in "100", it returns false.
    However, 100 has a 1 digit in it

    ReplyDelete
    Replies
    1. Indeed, the Solution at the top isn´t clean.

      Delete
  3. A more efficient way of doing that, Chris, is :

    public boolean hasOne(int n) {
    String num = Integer.toString(n);
    return num.contains("1");
    }

    ReplyDelete
  4. Another way of doing so:

    public boolean hasOne(int n) {
    return (String.valueOf(n).indexOf("1") != -1);
    }

    ReplyDelete
  5. recursively..

    public boolean hasOne(int n) {
    if(n < 1) return false;
    int x = n%10;
    if (x == 1) return true;
    else return hasOne(n/10);
    }

    ReplyDelete
  6. Your solution won't work for multiples of 10 other than 10.

    ReplyDelete
  7. public boolean hasOne(int n) {
    while(n>0){
    if(n%10==1) return true;
    else n=n/10;
    }
    return false;
    }

    ReplyDelete
  8. public boolean hasOne(int n) {
    return String.valueOf(n).contains("1");
    }

    ReplyDelete
  9. public boolean hasOne(int n) {
    return (i+"").contains("1");
    }

    ReplyDelete
  10. public boolean hasOne(int n) {
    for (; n > 0; n = n / 10 ) {
    if ( n % 10 == 1) return true;
    }
    return false;
    }

    ReplyDelete
  11. public boolean hasOne(int n) {
    if(n%10==1)return true;
    if(n==0)return false;
    return hasOne(n/10);
    }

    ReplyDelete
  12. String str = Integer.toString(n);
    return str.length()>str.replaceAll("1","").length();

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact