Skip to content
Related Articles

Related Articles

Python Program to Find Sum of First and Last Digit

View Discussion
Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 02 Aug, 2022
View Discussion
Improve Article
Save Article

Given a positive integer N(at least contain two digits). The task is to write a Python program to add the first and last digit of the given number N.

Examples:

Input: N = 1247
Output: 8

Explanation: First digit is 1 and Last digit is 7. 
So, addition of these two (1 + 7) is equal to 8.
Input: N = 73
Output: 10

Method 1: String implementation

  • Take input in the form of String or typecast given input in String.
  • Now pick the 0th index of the String and typecast it into Integer and store it in a variable.
  • The same thing with the -1st index and also store in another variable.
  • Now add these two variables and
  • print them as an Output.

Note:  We can access the first element of String using string[0] and the last element of String using string[-1].

String Representation


Python3




# We have a number
number = 1247
 
# We are type casting it in string
number = str(number)
 
# Storing first and last digit in a variable
# after type casting into Integer.
first_digit = int(number[0])
last_digit = int(number[-1])
 
# Adding these two variables
addition = first_digit + last_digit
 
# Display our output
print('Addition of first and last digit of the number is',
      addition)

Output:

Addition of first and last digit of the number is 8

Time complexity: O(1) since performing constant operations

Auxiliary Space: O(1) since using constant space for variables

Method 2: Solve it using an integer

  • We have given a positive Integer.
  • After dividing by 10, store the remainder in a result variable.
  • Continue the loop until the number becomes less than 9.
  • Each time in the loop, divide the number by 10(integer division).
  • After the end of the loop.
  • Add the number in the result variable.
  • Display the result variable as the output.

Note: Whenever we divide any number with 10, we get the last digit as the remainder. If we divide any number with 100, we get the last two-digit as the remainder.

Python3




# We have a number.
number = 1247
 
# Assigning last digit of the number in res
# variable.
res = number % 10
 
# Now, continue a loop until
# the number becomes less than 9.
while number > 9:
 
    # integer division of the number and reassigning
    # it.
    number = number // 10
 
# Here, our number only contain one digit.
# So, add this number in res variable.
res += number
 
# Now, display our output
print('Addition of first and last digit of number is', res)

Output:

Addition of first and last digit of the number is 8

Time Complexity: O(n), where n is how many digits are there in the given number.

Auxiliary Space: O(1) since using constant space for variables


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!