DEV Community

SILAMBARASAN A
SILAMBARASAN A

Posted on

DECIMAL NUMBERS

Decimal – Simple Definition

A decimal number is a number written using the base-10 system.

Decimal Numbers – Basic Idea

To break a decimal number (example: 2345) into digits:

  • no % 10 → gets the last digit
  • no // 10 → removes the last digit

This is the main logic used in all programs

SUM OF DIGITS

What does it do?
It adds all the digits in a number

Example:
2345 → 2 + 3 + 4 + 5 = 14

Loop Method

We use a while loop to add digits one by one

SUM OF DIGITS IN LOOP :

no=2345
sum=0
while no>0:
    sum=sum+no%10
    no=no//10
print(sum)
Enter fullscreen mode Exit fullscreen mode

OUTPUT :
14

Recursion Method

The function calls itself again and again to repeat the process

SUM OF DIGITS IN RECURSION :

def sum1(no,sum):
    if no>0:
        sum=sum+no%10
        no=no//10
        return sum1(no,sum)
    return sum
print(sum1(1234,0))
Enter fullscreen mode Exit fullscreen mode

OUTPUT :
10

COUNT OF DIGIT

What does it do?

It counts how many digits are in a number

Example:
2345 → 4 digits

Loop Method

In each step, we do count += 1

COUNT OF DIGITS IN LOOP :

no=2345
count=0
while no>0:
    count+=1
    no=no//10
print(count)
Enter fullscreen mode Exit fullscreen mode

OUTPUT :
4

COUNT OF DIGITS IN RECURSION :

Recursion Method

Idea:

count = 1 + count of remaining digits

def sum1(no,count):
    if no>0:
        count+=1
        no=no//10
        return sum1(no,count)
    return count
print(sum1(123437,0))
Enter fullscreen mode Exit fullscreen mode

OUTPUT :
6

NUMBER REVERSE

What does it do?

It reverses the number

Example:
2345 → 5432

Loop Method

reverse = reverse * 10 + last digit

NUMBER REVERSE IN LOOP :

no=2345
reverse=0
while no>0:
    reverse=reverse*10+no%10
    no=no//10
print(reverse)
Enter fullscreen mode Exit fullscreen mode

OUTPUT :
5432

NUMBER REVERSE IN RECURSION :

Recursion Method

Idea:
Take the last digit and build a new number step by step

def sum1(no,reverse):
    if no>0:
        reverse=reverse*10+no%10
        no=no//10
        return sum1(no,reverse)
    return reverse
print(sum1(123437,0))
Enter fullscreen mode Exit fullscreen mode

OUTPUT :
734321

Top comments (0)