Check Number Duck in Java
Problem
A Duck number is a number that contains at least one zero digit — since a stored int can never begin with a leading zero, checking every digit for a zero is sufficient.
Given a number, determine whether it is a Duck number.
Java Program
public class DuckNumberCheck {
public static void main(String[] args) {
int n = 3210;
boolean hasZero = false;
for (char ch : String.valueOf(n).toCharArray()) {
if (ch == '0') {
hasZero = true;
break; // found a zero digit, no need to check further
}
}
System.out.println(n + " is a Duck number: " + hasZero);
}
}Output
Core Logic
Converting the number to its string form and scanning every character for a zero checks the definition in a single pass.
- 1
String.valueOf(n).toCharArray()turns the number into its digit characters, in order. - 2A for-each loop checks whether any character equals
'0', settinghasZerototrueand stopping early withbreakthe moment one is found. - 3Every position is checked, including the first — a stored
intcan never actually begin with'0'unless the whole number is zero, so there's no risk of a false positive from the leading digit.
3210, the digits are 3, 2, 1, 0 — the last one matches '0', so hasZero becomes true.Key Point: Only the presence of a zero digit matters here, not its position — a number like 2005 and a number like 5002 are both Duck numbers for the same reason.
Why: The scan visits at most every digit of n once, stopping early the moment a zero is found.
Key Concepts
Approach 2: Using String Methods
public class DuckNumberCheckBuiltIn {
public static void main(String[] args) {
int n = 3210;
boolean hasZero = String.valueOf(n).contains("0");
System.out.println(n + " is a Duck number: " + hasZero);
}
}
Output
Core Logic
Java's String class can already search for a character directly, replacing the manual character-by-character scan with a single method call.
- 1
String.valueOf(n)converts the number to its string form, same as the manual version. - 2
.contains("0")searches the whole string for a zero character in one call.
3210, "3210".contains("0") returns true, matching the manual scan's result.Key Point: contains() still scans the string internally, so this doesn't change the underlying cost — it just replaces the explicit loop with a single built-in call.
Why: contains() still scans the string internally looking for a match, the same cost as the manual character loop.