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
anorbcontains the digit zeroa + b = n
Approach
Iterates through possible values of
afrom 1 ton-1Calculates
basn - aCheck both
aandbReturns 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