Do not convert number to other type. Do not use built-in functions like Contains()
, StartsWith()
, etc.
while (number > 0)
{
if (number % 10 == 3)
{
return true;
}
number /= 10;
}
return false;`
Method that checks if given number (positive integer) contains digit 3
You were nearly there
private static bool HasDigit(int num,int digit)
{
while (num > 0)
{
if(num % 10 == digit)
return true;
num /= 10;
}
return false;
}
Usage
Console.WriteLine(HasDigit(1222, 3));
Console.WriteLine(HasDigit(23345, 3));
Output
False
True
Other approaches might be
private static bool HasDigit2(int num, int digit)
{
var str = num.ToString();
for (int i = 0; i < str.Length; i++)
if (str[i] == ((char) digit) + '0')
return true;
return false;
}
Or
private static bool HasDigit3(int num, int digit)
=> num.ToString().Any(t => t == ((char) digit) + '0');
Here's a recursive solution:
public static bool Contains3(int n) {
if (n < 10) {
if (n == 3) {
return true;
} else {
return false;
}
}
return n % 10 == 3 || Contains3(n / 10);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.