
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Number of N-Digit Stepping Numbers in C++
The stepping number is a number where the difference between the consecutive digits is 1. You are given a number n representing the number of digits. You need to count the total number of stepping numbers with n digits.
Let's see an example.
Input
2
Output
17
The lowest number of 2 digits is 10 and highest number of 2 digits is 99. There are 17 stepping numbers in between them.
Algorithm
- Initialise the number n.
- Initialise the count to 0.
- Find the lowest number of n digits i.e.., pow(10, n - 1).
- Find the highest number of n digits i.e.., pow(10, n) - 1.
- Write a loop that iterates from the lowest n digit number to highest n digit number.
- Check whether the current number is stepping number or not.
- Check the difference between consecutive pair of digits in the number.
- If the result of the any difference is not 1, then return false else true.
- Increment the count if the current number is a stepping number.
- Return the count.
Implementation
Following is the implementation of the above algorithm in C++
#include <bits/stdc++.h> using namespace std; bool isSteppingNumber(int n) { int previousDigit = -1; while (n) { int currentDigit = n % 10; if (previousDigit != -1 && abs(previousDigit - currentDigit) != 1) { return false; } previousDigit = currentDigit; n /= 10; } return true; } int getSteppingNumbersCount(int n) { int lowestNumber = pow(10, n - 1), highestNumber = pow(10, n) - 1; int count = 0; for (int i = lowestNumber; i <= highestNumber; i++) { if (isSteppingNumber(i)) { count += 1; } } return count; } int main() { int n = 3; cout << getSteppingNumbersCount(n) << endl; return 0; }
Output
If you run the above code, then you will get the following result.
32
Advertisements