- Related Questions & Answers
- C Program to Check if all digits of a number divide it
- C Program for Print individual digits as words without using if or switch.
- Print first k digits of 1/n where n is a positive integer in C Program
- What is the difference between Enumeration interface and enum in Java?
- Absolute and Relative frequency in Pandas
- Absolute Deviation and Absolute Mean Deviation using NumPy
- What is the difference between throw e and throw new Exception(e) in catch block in java?
- What is the difference between selenium and automation?
- What is difference between selenium 1 and Selenium 2
- Difference between import and package in Java?
- Difference between the byte stream and character stream classes in Java?
- Array element with minimum sum of absolute differences?
- Arrange first N natural numbers such that absolute difference between all adjacent elements > 1?
- All possible numbers of N digits and base B without leading zeros?
- C/C++ Program to check whether it is possible to make a divisible by 3 number using all digits in an array?

- 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