Reverse a Number in C++ using Recursion.

Given a number num, write a C++ Program to reverse the given number using Recursion. 

Example:
Input: num = 1234
Output: 4321

Input: num = -345
Output: -543

To solve this problem, you must have some prior knowledge of C++ programming and Recursion.

Follow the steps given below to reverse a number using Recursion.
  • In the reverse function, we first check if the number is zero. If it is, we return from the function, as there's nothing to reverse.
  • If the number is not zero, we output the last digit of the number using the modulo operator (%).
  • We then call the reverse function again, passing the number divided by 10, to remove the last digit.
  • This process continues until the number becomes zero.
C++ code to Reverse a Positive Number.
//C++ Program to reverse positive number using Recursion
#include <iostream>
using namespace std;

//function call
void reverse(int num) {
    if (num == 0) {
        return;
    }

    cout << num % 10;
    reverse(num / 10);
}

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;

    cout << "The reverse of the number is: ";
    reverse(num);
    cout << endl;
    return 0;
}
Output:
Enter a number: 4738
The reverse of the number is: 8374
  • Time Complexity: O(log(n))
  • Auxiliary Space: O(log(n))
Note: The above algorithm can reverse only positive numbers so to reverse both positive and negative numbers, we have made some changes in the above algorithm. (alert-passed)


Reverse a Negative Number in C++

Following steps to reverse both positive and negative numbers using recursion:

  • If the number is not zero, we output the last digit of the number using the abs function and modulo operator (%).
  • We then call the reverse function again, passing the absolute value of the number divided by 10, to remove the last digit.
  • This process continues until the number becomes zero.
  • We read the input number and check if it's negative. If it is, we output a negative sign before calling the reverse function. 
C++ code to reverse both positive and negative numbers.

//C++ Program to reverse both positive and negative num
#include <iostream>
using namespace std;

//function call
void reverse(int num) {
    if (num == 0) {
        return;
    }

    cout << abs(num % 10);
    reverse(num / 10);
}

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;

    cout << "The reverse of the number is: ";
    //checking if num is negative
    if (num < 0) {
        cout << "-";
    }
    
    reverse(abs(num));
    cout << endl;
    return 0;
}
Output:
Enter a number: -14738
The reverse of the number is: -83741
  • Time Complexity: O(log(n))
  • Auxiliary Space: O(log(n))

C++ Program to Find Sum of Digits of a Number.

Digits of a Number

Given a number num, write a C++ Program to find the sum of digits of the number. 

Example:

Input: num = 1432
Output: 10

Explanation: 1 + 4 + 3 + 2 = 10

Input: num = 9831
Output: 21

Explanation: 9 + 8 + 3 + 1 = 21

There are multiple ways to solve this problem, let's understand each of them one by one:

Approach 1: Using the modulo operator and while loop.

Follow the below steps to sum the digits of a number:
  • Use a while loop to continuously extract the last digit of the number using the modulo operator (%).
  • Add the extracted digit to a running total (sum), and then remove it from the number using the division (/) operator.
  • This process continues until the number becomes zero.
C++ Program sums the digits of a number. 
//C++ Program to sum the digits of a number
#include <iostream>
using namespace std;

int main() {
    int num, sum = 0;
    cout << "Enter a number: ";
    cin >> num;

    while (num > 0) {
        sum += num % 10;
        num /= 10;
    }

    cout << "Sum of digits: " << sum << endl;
    return 0;
}
Output:
Enter a number: 1345
Sum of digits: 13
  • Time Complexity: O(n)
  • Space Complexity: O(1)

Approach 2: Using String Streams.

Follow the below steps:
  • Use a string stream to convert the integer number into a string. 
  • Use a for loop to iterate over each character in the string and add its integer value (obtained by subtracting the ASCII value of the character '0') to a running total (sum).
  • Print the value of the sum as an output.
C++ code implementation of the above approach.
//C++ code implementation for finding sum of diigts of a num
#include <iostream>
#include <sstream>

using namespace std;

int main() {
    int num, sum = 0;
    cout << "Enter a number: ";
    cin >> num;

    stringstream ss;
    ss << num;

    string str = ss.str();
    for (char c : str) {
        sum += c - '0';
    }

    cout << "Sum of digits: " << sum << endl;
    return 0;
}
Output:
Enter a number: 1349
Sum of digits: 17
  • Time Complexity: O(n)
  • Space Complexity: O(n)

C++ Program to Check Whether Number is Even or Odd.

Given a number num, write a C++ Program to check whether the given number is Even or Odd

Example:

Input: num = 8
Output: Even

Input: num = 11
Output: Odd

Note: To understand this example, you must know the basics of C++ programming and if..else statements. 

Approach 1: If the given number is divisible by 2 then the number is Even and if the number is not divisible by 2 then the number is Odd.

Pseudo Code:
Step 1: Read a number "num"
Step 2: If "num % 2" is equal to 0, then
    Step 2.1: Print "num is an even number"
Step 3: Else,
    Step 3.1: Print "num is an odd number"
Step 4: End

Following C++ Program to check if a number is Even or Odd:
//C++ Program to check Even or Odd
#include <iostream>
using namespace std;

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;

    if (num % 2 == 0) {
        cout << num << " is an even number" << endl;
    } else {
        cout << num << " is an odd number" << endl;
    }

    return 0;
}
Output:
Enter a number: 12
12 is an even number

Explanation: 
The program takes an input number and calculates the remainder when it is divided by 2. If the remainder is 0, then the number is even, and if it's not 0, then the number is odd.


Approach 2
In this approach, we use the bitwise "&" operator to check if the least significant bit (LSB) of the number is set. If the LSB is set, then the number is odd, and if it's not set, then the number is even. 

Below is the C++ code Implementation:
//C++ Program to check Odd and Even using Bitwise
#include <iostream>
using namespace std;

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;

    if (num & 1) {
        cout << num << " is an odd number" << endl;
    } else {
        cout << num << " is an even number" << endl;
    }

    return 0;
}
Output:
Enter a number: 11
11 is an odd number
NoteThis approach is faster than the modulo operator (%), as the bitwise operator is typically faster than the modulo operator. (alert-success)

Python Program to Add Item in a Tuple.

Tuples are immutable, meaning their values cannot be changed once they are created. This can be a disadvantage when you need to add an element to an existing tuple. To overcome this, there are several different approaches you can take to add an item to a tuple in Python:


Adding Item to Tuple

List of Approaches to Add Item in a Tuple.

1. Concatenation: One way to add an item to a tuple is to concatenate two tuples together using the + operator.

Example Code:

# Adding Item to Tuple Using Concatenation
original_tuple = (1, 2, 3)
new_item = 4
updated_tuple = original_tuple + (new_item,)

print(updated_tuple)
Output:
(1, 2, 3, 4)

Advantages and Disadvantages of Concatenation on Tuple.

Advantages:
  • Simple and easy to understand.
  • Suitable for adding a single item to a tuple.
Disadvantages:
  • Not efficient for adding multiple items to a tuple.
  • Creates a new tuple, which requires additional memory.

2. Conversion to a list: Another approach is to convert the tuple to a list, add the item to the list, and then convert the list back to a tuple.

Example Code:
# Adding Item to Tuple Using Conversion to a list
original_tuple = (1, 2, 3)
new_item = 4
updated_list = list(original_tuple)
updated_list.append(new_item)
updated_tuple = tuple(updated_list)

print(updated_tuple)
Output:
(1, 2, 3, 4)


Advantages and Disadvantages of Conversion of Tuple to List.

Advantages:
  • Suitable for adding multiple items to a tuple.
  • The append method can be used to add various items to the list.
Disadvantages:
  • Converting the list back to a tuple requires additional time and memory.
  • Not as efficient as other approaches for adding a single item to a tuple.

3. Using slicing: You can also create a new tuple by slicing the original tuple and adding the new item in between.

Example Code:
# Adding Item to Tuple Using Slicing 
original_tuple = (1, 2, 3)
new_item = 4
updated_tuple = original_tuple[:len(original_tuple)] + 
(new_item,) + original_tuple[len(original_tuple):]

print(updated_tuple)
Output:
(1, 2, 3, 4)

Advantages and Disadvantages of Slicing on Tuple.

Advantages:
  • Suitable for adding a single item to a tuple.
  • Does not require conversion to a list.
Disadvantages:
  • Complex and less readable than other approaches.
  • Creates a new tuple, which requires additional memory.

You can use all these approaches based on your requirement, which can be decided by the number of items that need to be added to the tuple and the size. 

Read more:

How To Add Elements to List in Python?

In this tutorial, we are going to understand different approaches to add elements to a list in Python. 

There are three different ways of adding elements to a List in Python. 

  • Using the append() method.
  • Using the extend() method.
  • Using the Concatenation operator (+).

Using the append() method.

In this approach, we use the append() method to add elements to the end of the list. The append() method takes one argument, which is the element to be added to the list.

Python code:

my_list = []
my_list.append(1)
my_list.append(2)
my_list.append(3)
print(my_list)  # Output: [1, 2, 3]

Using the extend() method.

In this approach, we use the extend() method to add multiple elements to the end of the list. The extend() method takes one argument, which is a list of elements to be added to the original list.

Python code:
my_list = [1, 2]
my_list.extend([3, 4, 5])
print(my_list)  # Output: [1, 2, 3, 4, 5]

Using the Concatenation operator (+).

In this approach, we use the concatenation operator + to add multiple elements to the end of the list. The concatenation operator takes two lists as operands and returns a new list which is the concatenation of the two lists.

Python code:
my_list = [1, 2]
my_list = my_list + [3, 4, 5]
print(my_list)  # Output: [1, 2, 3, 4, 5]

Python Program to Add Digits of a Number.

Given a number num, write a Python program to add digits of the given number and print the sum as an output.

Example:

Input: num = 145
Output: 10

Explanation: 1 + 4 + 5 = 10

Input: num = 9231
Output: 15

Explanation: 9 + 2 + 3 + 1 = 15

There are multiple approaches by which we can solve this problem, let's discuss each of them one by one.

Approach 1: Using integer division and modulo operator.

In this approach, we use the modulo operator % to extract the last digit of the number and add it to the sum variable. We then use integer division // to remove the last digit from the number and repeat the process until the number becomes zero.

Python code:
# Python program to add digits of a number
def add_digits(n):
    sum = 0
    while n > 0:
        sum += n % 10
        n = n // 10
    return sum

# take input from the user
num = int(input("Enter a number: "))  

print(add_digits(num))    
Output:
Enter a number: 123
6
  • Time Complexity: O(number of digits)
  • Space Complexity: O(1)

Approach 2: Using string conversion and for loop.

In this approach, we first convert the number to a string and then use a for loop to iterate over each character in the string. We convert each character back to an integer and add it to the sum variable.

Python code:
# Python program to add digits of a number
def add_digits(n):
    n = str(n)
    sum = 0
    for digit in n:
        sum += int(digit)
    return sum

# take input from the user
num = int(input("Enter a number: "))  

print(add_digits(num))    
Output:
Enter a number: 4753
19
  • Time Complexity: O(number of digits)
  • Space Complexity: O(1)

Approach 3: Using Recursion.

In this approach, we use recursion, to sum up, the digits of the number. The base case is when the number becomes zero, in which case we return zero. Otherwise, we extract the last digit using the modulo operator and add it to the result of the recursive call to add_digits with the number divided by 10.

Python Code:
# Python program to add digits of a number
def add_digits(n):
    if n == 0:
        return 0
    return n % 10 + add_digits(n // 10)

# take input from the user
num = int(input("Enter a number: "))  

print(add_digits(num))    
Output:
Enter a number: 542
11
  • Time Complexity: O(number of digits)
  • Space Complexity: O(n) 

Read more:

Python Program to Reverse a Number.

Given a number num, you need to write a Python Program to print the number in reverse. 

Example:

Input: num = 1372
Output: 2731

Input: num = 901
Output: 109

There are multiple approaches to solving this problem, let's discuss each of them one by one:

Reverse a number using String Slicing in Python.

Python slicing technique is one important feature that is used for extracting a portion of a string, a list of tuples. We can use this notation to reverse the given number.

Steps to do so:
  • The function takes the input num and converts it to a string.
  • The function then uses slicing to reverse the string and returns the result as an integer.
  • The program then takes input from the user and stores it in the num variable.
Python Code:
def reverse_number(num):
    return int(str(num)[::-1])

# take input from the user
num = int(input("Enter a number: "))

# reverse the number
rev = reverse_number(num)

# print the reversed number
print("The reversed number is", rev)
Output:
Enter a number: 1348
The reversed number is 8431


Reverse a number using a while loop in Python.

We can use any loop to iterate through each digit of the given number and perform some mathematical operations to reverse their order and generate a new reverse number. 

Steps to do so:
  • The program defines a function reverse_number to reverse a given number.
  • The function initializes two variables rev and rem to store the reversed number and the remainder of the number.
  • The function then uses a while loop to reverse the number digit by digit.
  • In each iteration, the function calculates the remainder of the number by dividing it by 10 and stores it in rem.
  • The function then multiplies the current value of rev by 10 and adds rem to it.
  • The function then updates the value of num by dividing it by 10.
  • The function repeats these steps until num is 0.
Python Code:
def reverse_number(num):
    rev = 0
    while num > 0:
        rem = num % 10
        rev = rev * 10 + rem
        num = num // 10
    return rev

# take input from the user
num = int(input("Enter a number: "))

# reverse the number
rev = reverse_number(num)

# print the reversed number
print("The reversed number is", rev)
Output:
Enter a number: 034
The reversed number is 43


Reverse a number using Recursion in Python.

This approach is the same as the previous one, In this approach, we are using recursion to iterate through each digit of the given number.
 
Steps to do so:
  • The function takes two inputs: num and rev, where num is the number to be reversed and rev is the reversed number so far.
  • The function uses an if statement to check if num is 0. If num is 0, the function returns rev.
  • If num is not 0, the function calculates the remainder of num by dividing it by 10 and stores it in rem.
  • The function then calls itself with num // 10 and rev * 10 + rem as inputs and returns the result.
Python Code:
def reverse_number(num, rev=0):
    if num == 0:
        return rev
    rem = num % 10
    return reverse_number(num // 10, rev * 10 + rem)

# take input from the user
num = int(input("Enter a number: "))

# reverse the number
rev = reverse_number(num)

# print the reversed number
print("The reversed number is", rev)
Output:
Enter a number: 2034
The reversed number is 4302
  • Time Complexity: O(n) where n is the number of digits that the number contains.
  • Space Complexity: O(n) stack space is required for performing recursion.

Python Program to Check Armstrong Number.

Given a number x, write a Python program to check whether the given number is an Armstrong number or not. 

An Armstrong number, also known as a narcissistic number or a pluperfect digital invariant, is a number that is equal to the sum of its own digits raised to the power of the number of digits. ()


For example, the number 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153.

Example:

Input: num = 1634
Output: 1634 is an Armstrong Number.

Explanation: 1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1634

Input: num = 130
Output: 130 is not an Armstrong Number.

Explanation: 1*1*1 + 3*3*3 + 0*0*0 = 28


Python Program to check if the given number is Armstrong Number.

def is_armstrong_number(number):
    # convert the number to a string and find the number of digits
    num_str = str(number)
    num_digits = len(num_str)

    # initialize a variable to store the sum of the digits raised to the power of the number of digits
    sum_of_digits = 0

    # loop through each digit in the number
    for digit in num_str:
        # raise the digit to the power of the number of digits and add it to the sum
        sum_of_digits += int(digit) ** num_digits

    # return True if the sum is equal to the number, and False otherwise
    return sum_of_digits == number

# take input from the user
number = int(input("Enter a number: "))

# check if the number is an Armstrong number
if is_armstrong_number(number):
    print(number, "is an Armstrong number.")
else:
    print(number, "is not an Armstrong number.")
Output:
Enter a number: 153
153 is an Armstrong number.
  • Time Complexity: O(log n)
  • Space Complexity: O(1)
Code Explanation
  • The program defines a function is_armstrong_number to check if a given number is an Armstrong number.
  • The function first converts the number to a string and finds the number of digits by finding the length of the string.
  • The function then initializes a variable sum_of_digits to store the sum of the digits raised to the power of the number of digits.
  • The function then loops through each digit in the number, raises the digit to the power of the number of digits, and adds the result to the sum_of_digits.
  • The function then returns True if the sum_of_digits is equal to the original number, and False otherwise.

Read More:

DON'T MISS

Nature, Health, Fitness
© all rights reserved
made with by AlgoLesson