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
Absolute difference between the first X and last X Digits of N?
Here we will see how to get the differences between first and last X digits of a number N. The number and X are given. To solve this problem, we have to find the length of the number, then cut the last x digits using modulus operator. After that cut all digits from the number except first x digits. Then get the difference, and return the result. Let the number is N = 568424. The X is 2 so first two digits are 56, and last two digits are 24. The difference is (56 - 24) = 32.
Algorithm
diffFirstLastDigits(N, X)
begin p := 10^X last := N mod p len := length of the number N while len is not same as X, do N := N / 10 len := len -1 done first := len return |first - last| end
Example
#include <iostream>
#include <cmath>
using namespace std;
int lengthCount(int n){
return floor(log10(n) + 1);
}
int diffFirstLastDigits(int n, int x) {
int first, last, p, len;
p = pow(10, x);
last = n % p;
len = lengthCount(n);
while(len != x){
n /= 10;
len--;
}
first = n;
return abs(first - last);
}
main() {
int n, x;
cout << "Enter number and number of digits from first and last: ";
cin >> n >> x;
cout << "Difference: " << diffFirstLastDigits(n,x);
}
Output
Enter number and number of digits from first and last: 568424 2 Difference: 32
Advertisements