Find Range (Max-Min) of Odd Digits

Numbers, in their myriad combinations, weave a tapestry of patterns and stories. One such fascinating tale is that of odd digits. In this intriguing challenge, you’ll dive deep into the world of numbers to uncover the peaks and troughs of odd digits within them.

Your task is to find the range of odd digits in a given number. The range is defined as the difference between the maximum and minimum odd digit present in the number. If there are no odd digits in the number, return -1.

Boundary Condition(s):
10 <= N <= 10^9

Input Format:
A single integer N, the number you need to analyze.

Output Format:
An integer representing the range of odd digits or -1 if no odd digits are present.

Example Input/Output 1:
Input:
1492057

Output:
6

Explanation:
The odd digits in the number are 1, 9, 5, and 7. The range is 9 (maximum odd digit) minus 1 (minimum odd digit) which equals 8.

n = input().strip()
odd_digits = [int(digit) for digit in n if int(digit) % 2 == 1]
if odd_digits:
    print(max(odd_digits) - min(odd_digits))
else:
    print(-1)
#include<stdio.h>

int main() {
    char n[10];
    int max_odd = -1, min_odd = 11;
    scanf("%s", n);
    for(int i = 0; n[i] != ''; i++) {
        int digit = n[i] - '0';
        if (digit % 2 == 1) {
            if (digit > max_odd) max_odd = digit;
            if (digit < min_odd) min_odd = digit;
        }
    }
    if (max_odd != -1) {
        printf("%d", max_odd - min_odd);
    } else {
        printf("-1");
    }
    return 0;
}
#include <iostream>
using namespace std;

int main() {
    string n;
    int max_odd = -1, min_odd = 11;
    cin >> n;
    for(char digit : n) {
        int val = digit - '0';
        if (val % 2 == 1) {
            if (val > max_odd) max_odd = val;
            if (val < min_odd) min_odd = val;
        }
    }
    if (max_odd != -1) {
        cout << max_odd - min_odd;
    } else {
        cout << "-1";
    }
    return 0;
}
import java.util.Scanner;

public class OddDigitsRange {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String n = sc.next();
        int max_odd = -1, min_odd = 11;
        for(char digit : n.toCharArray()) {
            int val = digit - '0';
            if (val % 2 == 1) {
                if (val > max_odd) max_odd = val;
                if (val < min_odd) min_odd = val;
            }
        }
        if (max_odd != -1) {
            System.out.println(max_odd - min_odd);
        } else {
            System.out.println("-1");
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

More posts. You may also be interested in.