View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
Given a number and to find first and last digit of a number.
Examples:
Input : 12345 Output : First digit: 1 last digit : 5 Input : 98562 Output : First digit: 9 last digit : 2
To find last digit of a
number, we use modulo operator %. When modulo divided by 10 returns its last digit.
Suppose if n = 1234
then last Digit = n % 10 => 4
To finding first digit of a number is little expensive than last digit. To find first digit of a number we divide the given number by 10 until number is greater than 10. At the end we are left with the first digit.
Approach 1 [With loop]:
C++
#include
using
namespace
std;
int
firstDigit[
int
n]
{
while
[n >= 10]
n /= 10;
return
n;
}
int
lastDigit[
int
n]
{
return
[n % 10];
}
int
main[]
{
int
n = 98562;
cout
Javascript
function
firstDigit[n]
{
let digits = Math.floor[Math.log[n]/Math.log[10]]
n = Math.floor[n / Math.pow[10, digits]]
return
n;
}
function
lastDigit[n]{
return
[n % 10]
}
let n = 98562;
document.write[firstDigit[n],
" "
]
document.write[lastDigit[n],
""
]
Time Complexity: O[1]
Auxiliary Space: O[1]
Important note: log10[] is a mathematical function present in math.h header file. It returns log base 10 value of the passed parameter to log10[] function.