In the previous article, we explored Global Variables in Python, now we will look at how we can obtain the first digit of any given number. We have also seen how we can obtain the last digit of a number in an older different article. For example, if the input values are:
- 7549: It should return 7
- 8: It should return 8
- 34: It should return 3
Let us see a basic algorithm on how we can write or implement a program, the idea is simple. We can remove the last digit by dividing by 10 and we stop until we have a single digit left which would be the first digit of the given number.
As with the first number from earlier, suppose the value provided is 7549 the logic would be to divide until we obtain 7.
x=7549
x=x//10=754
x=x//10=75
x=x//10=7
Implementation of Find First Digit of a Number Python program algorithm
We need to make use of the division technique to divide until the number is a single digit, we can achieve this through the use of looping statements:
def getFirstDigit(x):
while x>=10:
x=x//10
return x
x=int(input("Enter x:"))
print(getFirstDigit(x))
In the above program, the looping statement checks if the number is less than 10, it is less it proceeds to return the number as the output, if it is greater than 10 the looping statement continues its successive iterations until a number less than 10 is obtained.
Method 2: Using log
We have the number x whose first digit is to be found out, we can do so through the log of the number. If we find out the log of the number it gives us the total number of digits -1. For example, we find out the log of 1000 base 10. We are going to obtain an output of 3, and if we obtain the log of any number greater than 1000 and less than 10,000 we will get the log between 3 and 4 since once we reach 10,000 the log is 4. If there are a total of 5 digits, then we get the value of the log as 4 or greater than 4 yet less than 5.
Suppose with the value of 7549, we would get a log value of 3.88(floating point) the number is going to be greater than 3 or smaller than 4. If we take it in integer format, we have all the digits after the decimal point is removed.
If we multiply the number 10 with the power of the log value(10**3) and then divide the original number with the result we would get the value of the first digit.
import math
def getFirstDigit(x):
d=int(math.logo(x))
res=x//(10**d)
return res
x=int(input("Enter x:"))
print(getFirstDigit(x))
Output:
Enter x:789
7
So this is an alternate solution obtained through the use of library functions. In the next article, we will look at implementing Prime Factorization.