- 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++
- 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?
- Program to find sum of 1 + x/2! + x^2/3! +…+x^n/(n+1)! in C++
- Find minimum x such that (x % k) * (x / k) == n in C++
- Find the number of integers x in range (1,N) for which x and x+1 have same number of divisors in C++
- What are the key differences between Python 2.7.x and Python 3.x?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

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

#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); }

Enter number and number of digits from first and last: 568424 2 Difference: 32

Advertisements