The program must accept an integer N as the input. The task is to count and print the number of digits in N whose position (from the rightmost side) is the same as the digit itself. If no such digits are found, print -1.
Note: Position starts from 1 from the rightmost side.
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 whose position (from the rightmost side) is the same as the digit itself or -1.
Example Input/Output 1:
Input:
3412
Output:
2
Explanation:
The digit 1 is in the 1st position (from the rightmost side) and the digit 2 is in the 2nd position. Hence the count is 2.
Example Input/Output 2:
Input:
4567
Output:
-1
Explanation:
There are no digits whose position (from the rightmost side) is the same as the digit itself.
n = input().strip()
count = sum(1 for idx, digit in enumerate(reversed(n), 1) if int(digit) == idx)
print(count if count > 0 else -1)
#include<stdio.h>
#include<string.h>
int main() {
char n[12];
scanf("%s", n);
int len = strlen(n);
int count = 0;
for(int i = 0; i < len; i++) {
if(n[len - i - 1] - '0' == 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 = 0; i < n.size(); i++) {
if(n[n.size() - i - 1] - '0' == i + 1) count++;
}
cout << (count > 0 ? count : -1);
return 0;
}
import java.util.Scanner;
public class CountInvertedDigits {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String n = sc.next();
int count = 0;
for(int i = 0; i < n.length(); i++) {
if(n.charAt(n.length() - i - 1) - '0' == i + 1) count++;
}
System.out.println(count > 0 ? count : -1);
}
}
Leave a Reply