Convert Integer to the Sum of Two No-Zero Integers

Description

Given an integer n, find two positive integers a and b such that:

  • Neither a nor b contains the digit zero

  • a + b = n

Description

Approach

  • Iterates through possible values of a from 1 to n-1

  • Calculates b as n - a

  • Check both a and b

  • Returns the first valid pair found

Implementation

Java

class Solution {
    private boolean hasNoZero(int num) {
        return !String.valueOf(num)
            .chars()
            .mapToObj(ch -> (char)ch)
            .anyMatch(ch -> ch == '0');
    }
    
    public int[] getNoZeroIntegers(int n) {
        return java.util.stream.IntStream
            .rangeClosed(1, n-1)
            .filter(a -> {
                int b = n - a;
                return hasNoZero(a) && hasNoZero(b);
            })
            .mapToObj(a -> new int[]{a, n-a})
            .findFirst()
            .orElse(new int[]{});
    }
}

C++

Rust

Go

Complexity

  • Time Complexity: O(n)

  • Space Complexity: O(1)

Last updated