
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
Find the Slope of a Given Number Using C++
In this problem, we are given a number N. Our task is to find the slope of the given number.
Slope of a number is the total number of maxima and minima digits in the number.
Maxima digit is the digit whose both neighbours (previous and next) are smaller.
Maxima digit is the digit whose both neighbours (previous and next) are greater.
Let’s take an example to understand the problem,
Input
N = 9594459
Output
2
Solution Approach
A simple solution to the problem is by traversing the number digit by digit from excluding the first and last one (the don’t count form maxima or minima). Now, for each digit, we will check whether the digits are greater or smaller than digits before and after it. At last, we will return the maxima and minima count.
Example
Program to illustrate the working of our solution
#include <iostream> using namespace std; int findNumberSlope(string N, int len){ int slope = 0; for (int i = 1; i < len - 1; i++) { if (N[i] > N[i - 1] && N[i] > N[i + 1]) slope++; else if (N[i] < N[i - 1] && N[i] < N[i + 1]) slope++; } return slope; } int main(){ string N = "574473434329"; int len = N.size(); cout<<" The slope of the given number is "<<findNumberSlope(N, len); return 0; }
Output
The slope of the given number is 7