Java ProgramsControl FlowCheck Number Duck

Check Number Duck in Java

beginner·  Control Flow  ·  Loops

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.

Input
3210
Output
3210 is a Duck number: true

Java Program

Java
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

3210 is a Duck number: true

Core Logic

Converting the number to its string form and scanning every character for a zero checks the definition in a single pass.

How It Works
  1. 1String.valueOf(n).toCharArray() turns the number into its digit characters, in order.
  2. 2A for-each loop checks whether any character equals '0', setting hasZero to true and stopping early with break the moment one is found.
  3. 3Every position is checked, including the first — a stored int can never actually begin with '0' unless the whole number is zero, so there's no risk of a false positive from the leading digit.
For 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.

Complexity
Time Complexity: O(d)Space Complexity: O(1)

Why: The scan visits at most every digit of n once, stopping early the moment a zero is found.

Key Concepts

String.valueOf()char arraycharacter comparison

Approach 2: Using String Methods

Java
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

3210 is a Duck number: true

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.

How It Works
  1. 1String.valueOf(n) converts the number to its string form, same as the manual version.
  2. 2.contains("0") searches the whole string for a zero character in one call.
For 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.

Complexity
Time Complexity: O(d)Space Complexity: O(1)

Why: contains() still scans the string internally looking for a match, the same cost as the manual character loop.

Key Concepts

String.contains()

Related Programs