Count of Digits That Are Less Than Previous Digit

The program must accept an integer N as the input. The task is to count and print the number of digits in N that are less than their immediate previous digit. If no such digits are found, print -1.

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

Input Format:
The first line contains the integer N.

Output Format:
The first line contains either the count of the digits that are less than their immediate previous digit or -1.

Example Input/Output 1:
Input:
123421

Output:
1

Explanation:
Only the digit 1 in the number 123421 is less than its previous digit which is 2. Hence the count is 1.

Example Input/Output 2:
Input:
98765

Output:
4

Explanation:
All the digits except the first one are less than their immediate previous digits. Hence the count is 4.

n = input().strip()
count = sum(1 for i in range(1, len(n)) if n[i] < n[i-1])
print(count if count > 0 else -1)
#include<stdio.h>

int main() {
    char n[12];
    scanf("%s", n);
    int count = 0;
    for(int i = 1; n[i]; i++) {
        if(n[i] < n[i-1]) count++;
    }
    printf("%d", (count > 0 ? count : -1));
    return 0;
}
#include <iostream>
#include <string>
using namespace std;

int main() {
    string n;
    cin >> n;
    int count = 0;
    for(int i = 1; i < n.size(); i++) {
        if(n[i] < n[i-1]) count++;
    }
    cout << (count > 0 ? count : -1);
    return 0;
}
import java.util.Scanner;

public class CountLessThanPrevDigits {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String n = sc.next();
        int count = 0;
        for(int i = 1; i < n.length(); i++) {
            if(n.charAt(i) < n.charAt(i-1)) count++;
        }
        System.out.println(count > 0 ? count : -1);
    }
}

Leave a Reply

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

More posts. You may also be interested in.