

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Questions & Answers
- Difference between x++ and x = x+1 in Java
- Difference between x++ and x= x+1 in Java programming
- Construct a frequency array of digits of the values obtained from x^1, x^2, ....., x^n in C++
- Find the Number of Solutions of n = x + n x using C++
- Sum of the Series 1 + x/1 + x^2/2 + x^3/3 + .. + x^n/n in C++
- Difference between NumberLong(x) and NumberLong(“x”) in MongoDB?
- Count of values of x <= n for which (n XOR x) = (n – x) 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 a number x such that sum of x and its digits is equal to given n using C++.
- Find a number x such that sum of x and its digits is equal to given n in C++
- Differences between Python 2.x and Python 3.x?
- Recursive sum of digit in n^x, where n and x are very large in C++
- Absolute difference of corresponding digits in JavaScript
- Program to find sum of 1 + x/2! + x^2/3! +…+x^n/(n+1)! in C++
Advertisements