DEV Community

Pavitha Pari
Pavitha Pari

Posted on

Find the next number containg all odd digits

Just a simple problem:

Input: 1233

Output: 1311

Explanation: This is the next smallest integer containing all odd digits.


Approach 01 (Brute-force)

Check each number incrementally to see if all digits are odd. Works, but very inefficient for large numbers.


Approach 02 (Digit-wise)

  1. Store the digits of n+1 as a list.
  2. Scan digits left to right.
    • If a digit is even → change it to the next odd.
    • Replace all digits after it with 1 to get the smallest valid number.

python
n = int(input())
lis = []
temp = n + 1

# Convert number to list of digits
while temp != 0:
    lis.append(temp % 10)
    temp //= 10
lis = lis[::-1]

# Process digits
for i in range(len(lis)):
    if lis[i] % 2 == 0:
        lis[i] += 1  # Change first even digit to next odd
        # Replace all following digits with 1
        for j in range(i+1, len(lis)):
            lis[j] = 1
        break  # Only need to fix the first even digit

# Convert list back to integer
result = int(''.join(map(str, lis)))
print(result)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)