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; }
I realize your solution was probably preferable, but I found another way:
ReplyDeletepublic boolean hasOne(int n) {
String nString = n + "";
return nString.contains("1");
}
public static boolean m1(int n)
Delete{
while(0<n)
{
if(n%10 == 1)
return true;
else
n/=10;
}
return false;
}
If you put in "100", it returns false.
ReplyDeleteHowever, 100 has a 1 digit in it
Indeed, the Solution at the top isn´t clean.
DeleteA more efficient way of doing that, Chris, is :
ReplyDeletepublic boolean hasOne(int n) {
String num = Integer.toString(n);
return num.contains("1");
}
Thats so smart!
DeleteAnother way of doing so:
ReplyDeletepublic boolean hasOne(int n) {
return (String.valueOf(n).indexOf("1") != -1);
}
recursively..
ReplyDeletepublic boolean hasOne(int n) {
if(n < 1) return false;
int x = n%10;
if (x == 1) return true;
else return hasOne(n/10);
}
Your solution won't work for multiples of 10 other than 10.
ReplyDeletepublic boolean hasOne(int n) {
ReplyDeletewhile(n>0){
if(n%10==1) return true;
else n=n/10;
}
return false;
}
public boolean hasOne(int n) {
ReplyDeletereturn String.valueOf(n).contains("1");
}
public boolean hasOne(int n) {
ReplyDeletereturn (i+"").contains("1");
}
public boolean hasOne(int n) {
ReplyDeletefor (; n > 0; n = n / 10 ) {
if ( n % 10 == 1) return true;
}
return false;
}
public boolean hasOne(int n) {
ReplyDeleteif(n%10==1)return true;
if(n==0)return false;
return hasOne(n/10);
}
String str = Integer.toString(n);
ReplyDeletereturn str.length()>str.replaceAll("1","").length();