- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- Difference between x++ and x = x+1 in Java
- Construct a frequency array of digits of the values obtained from x^1, x^2, ....., x^n\n in C++
- Difference between x++ and x= x+1 in Java programming
- Print all n-digit numbers with absolute difference between sum of even and odd digits is 1 in C++
- Absolute difference of corresponding digits in JavaScript
- Arrange first N natural numbers such that absolute difference between all adjacent elements > 1?
- Difference between NumberLong(x) and NumberLong(“x”) in MongoDB?
- Find a number x such that sum of x and its digits is equal to given n in C++
- Find a number x such that sum of x and its digits is equal to given n using C++.
- Count numbers with same first and last digits in C++
- Find the node whose absolute difference with X gives maximum value in C++
- Maximum difference between first and last indexes of an element in array in C
- Python Program to Generate a Dictionary that Contains Numbers (between 1 and n) in the Form (x,x*x).
- Difference between %p and %x in C/C++
- Find the Number of Solutions of n = x + n x using C++

Advertisements