The Wayback Machine - https://web.archive.org/web/20241006095248/https://www.geeksforgeeks.org/write-a-program-to-reverse-digits-of-a-number/
Open In App

Write a program to reverse digits of a number

Last Updated : 18 Oct, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Basic
46.92%
90K

Write a program to reverse the digits of an integer.

Image

Examples :  

Input : num = 12345
Output: 54321

Input : num = 876
Output: 678

Flowchart:  

Image

ITERATIVE WAY 

Algorithm:

Input:  num
(1) Initialize rev_num = 0
(2) Loop while num > 0
     (a) Multiply rev_num by 10 and add remainder of num  
          divide by 10 to rev_num
               rev_num = rev_num*10 + num%10;
     (b) Divide num by 10
(3) Return rev_num

Example: 

num = 4562 
rev_num = 0
rev_num = rev_num *10 + num%10 = 2 
num = num/10 = 456
rev_num = rev_num *10 + num%10 = 20 + 6 = 26 
num = num/10 = 45
rev_num = rev_num *10 + num%10 = 260 + 5 = 265 
num = num/10 = 4
rev_num = rev_num *10 + num%10 = 2650 + 4 = 2654 
num = num/10 = 0

Program: 

C




#include <stdio.h>
  
/* Iterative function to reverse digits of num*/
int reverseDigits(int num)
{
    int rev_num = 0;
    while (num > 0) {
        rev_num = rev_num * 10 + num % 10;
        num = num / 10;
    }
    return rev_num;
}
  
/*Driver program to test reverseDigits*/
int main()
{
    int num = 4562;
    printf("Reverse of no. is %d", reverseDigits(num));
  
    getchar();
    return 0;
}


C++




#include <bits/stdc++.h>
  
using namespace std;
/* Iterative function to reverse digits of num*/
int reverseDigits(int num)
{
    int rev_num = 0;
    while (num > 0) {
        rev_num = rev_num * 10 + num % 10;
        num = num / 10;
    }
    return rev_num;
}
  
/*Driver program to test reverseDigits*/
int main()
{
    int num = 4562;
    cout << "Reverse of no. is " << reverseDigits(num);
    getchar();
    return 0;
}
  
// This code is contributed
// by Akanksha Rai(Abby_akku)


Java




// Java program to reverse a number
  
class GFG {
    /* Iterative function to reverse
    digits of num*/
    static int reverseDigits(int num)
    {
        int rev_num = 0;
        while (num > 0) {
            rev_num = rev_num * 10 + num % 10;
            num = num / 10;
        }
        return rev_num;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int num = 4562;
        System.out.println("Reverse of no. is "
                           + reverseDigits(num));
    }
}
  
// This code is contributed by Anant Agarwal.


Python




# Python program to reverse a number
  
n = 4562
rev = 0
  
while(n > 0):
    a = n % 10
    rev = rev * 10 + a
    n = n // 10
  
print(rev)
  
# This code is contributed by Shariq Raza


C#




// C# program to reverse a number
using System;
  
class GFG {
    // Iterative function to
    // reverse digits of num
    static int reverseDigits(int num)
    {
        int rev_num = 0;
        while (num > 0) {
            rev_num = rev_num * 10 + num % 10;
            num = num / 10;
        }
        return rev_num;
    }
  
    // Driver code
    public static void Main()
    {
        int num = 4562;
        Console.Write("Reverse of no. is "
                      + reverseDigits(num));
    }
}
  
// This code is contributed by Sam007


PHP




<?php
// Iterative function to 
// reverse digits of num
function reverseDigits($num)
{
    $rev_num = 0;
    while($num > 1)
    {
        $rev_num = $rev_num * 10 + 
                        $num % 10;
        $num = (int)$num / 10;
    }
    return $rev_num;
}
  
// Driver Code
$num = 4562;
echo "Reverse of no. is "
       reverseDigits($num);
  
// This code is contributed by aj_36
?>


Javascript




<script>
    let num = 4562;
    // Function to reverse digits of num
    function reverseDigits(num) {
        let rev_num = 0;
        while(num > 0)
        {
            rev_num = rev_num * 10 + num % 10;
            num = Math.floor(num / 10);
        }
        return rev_num;
    }
 // function call   
    document.write(reverseDigits(num));
      
// This code is contributed by Surbhi tyagi
  
</script>


Output

Reverse of no. is 2654

Time Complexity: O(log10 n), where n is the input number. 
Auxiliary Space: O(1)

 

RECURSIVE WAY :

C




// C program to reverse digits of a number
#include <stdio.h>
  
/* Recursive function to reverse digits of num*/
int reverseDigits(int num)
{
    static int rev_num = 0;
    static int base_pos = 1;
    if (num > 0) {
        reverseDigits(num / 10);
        rev_num += (num % 10) * base_pos;
        base_pos *= 10;
    }
    return rev_num;
}
  
/*Driver program to test reverse Digits*/
int main()
{
    int num = 4562;
    printf("Reverse of no. is %d", reverseDigits(num));
  
    getchar();
    return 0;
}


C++




// C++ program to reverse digits of a number
#include <bits/stdc++.h>
using namespace std;
/* Recursive function to reverse digits of num*/
int reverseDigits(int num)
{
    static int rev_num = 0;
    static int base_pos = 1;
    if (num > 0) {
        reverseDigits(num / 10);
        rev_num += (num % 10) * base_pos;
        base_pos *= 10;
    }
    return rev_num;
}
  
// Driver Code
int main()
{
    int num = 4562;
    cout << "Reverse of no. is " << reverseDigits(num);
  
    return 0;
}
  
// This code is contributed
// by Akanksha Rai(Abby_akku)


Java




// Java program to reverse digits of a number
  
// Recursive function to
// reverse digits of num
class GFG {
    static int rev_num = 0;
    static int base_pos = 1;
    static int reverseDigits(int num)
    {
        if (num > 0) {
            reverseDigits(num / 10);
            rev_num += (num % 10) * base_pos;
            base_pos *= 10;
        }
        return rev_num;
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        int num = 4562;
        System.out.println(reverseDigits(num));
    }
}
  
// This code is contributed by mits


Python3




# Python 3 program to reverse digits
# of a number
rev_num = 0
base_pos = 1
  
# Recursive function to reverse
# digits of num
  
  
def reverseDigits(num):
    global rev_num
    global base_pos
    if(num > 0):
        reverseDigits((int)(num / 10))
        rev_num += (num % 10) * base_pos
        base_pos *= 10
    return rev_num
  
  
# Driver Code
num = 4562
print("Reverse of no. is ",
      reverseDigits(num))
  
# This code is contributed by Rajput-Ji


C#




// C# program to reverse digits of a number
  
// Recursive function to
// reverse digits of num
using System;
class GFG {
    static int rev_num = 0;
    static int base_pos = 1;
    static int reverseDigits(int num)
    {
        if (num > 0) {
            reverseDigits(num / 10);
            rev_num += (num % 10) * base_pos;
            base_pos *= 10;
        }
        return rev_num;
    }
  
    // Driver Code
    public static void Main()
    {
        int num = 4562;
        Console.WriteLine(reverseDigits(num));
    }
}
  
// This code is contributed
// by inder_verma


PHP




<?php
// PHP program to reverse digits of a number
$rev_num = 0; 
$base_pos = 1;
  
/* Recursive function to 
reverse digits of num*/
function reversDigits($num
    global $rev_num
    global $base_pos
    if($num > 0) 
    
        reverseDigits((int)($num / 10)); 
        $rev_num += ($num % 10) * 
                     $base_pos
        $base_pos *= 10; 
    
    return $rev_num
  
// Driver Code
$num = 4562; 
echo "Reverse of no. is "
       reverseDigits($num); 
  
// This code is contributed by ajit
?>


Javascript




<script>
  
// Javascript program to reverse digits of a number
  
/* Recursive function to reverse digits of num*/
var rev_num = 0;
var base_pos = 1;
function reversDigits(num)
{
  
    if(num > 0)
    {
        reverseDigits(Math.floor(num/10));
        rev_num += (num%10)*base_pos;
        base_pos *= 10;
    }
    return rev_num;
}
  
// Driver Code
    let num = 4562;
    document.write("Reverse of no. is "
        + reverseDigits(num));
  
// This code is contributed 
// by Mayank Tyagi
  
  
</script>


Output

Reverse of no. is 2654

Time Complexity: O(log(n)) 
Auxiliary Space: O(log(n)),  where n is the input number.

Using Recursion, without extra variable

C++




#include <iostream>
#include <math.h>
using namespace std;
  
// util functions
int len(int number)
{
    // returns the length of a given number
    return log10(number) + 1;
}
  
// reverse a given number
int rev_number(int& number)
{
    if ((number % 10) == number)
        return number;
    int last = number % 10;
    int remaining = number / 10;
    int l = len(remaining);
    return last * pow(10, l) + rev_number(remaining);
}
  
int main()
{
    int number = 123456;
    cout << rev_number(number) << endl;
    return 0;
}


Java




import java.lang.Math;
import java.util.*;
  
class GFG {
  
    public static int len(int number)
    {
        // returns the length of a given number
        return (int)(Math.log10(number)) + 1;
    }
  
    // reverse a given number
    public static int rev_number(int number)
    {
        if (number % 10 == number) {
            return number;
        }
  
        int last = number % 10;
        int remaining = number / 10;
        int l = len(remaining);
        return last * (int)Math.pow(10, l)
            + rev_number(remaining);
    }
  
    public static void main(String[] args)
    {
        int number = 123456;
        System.out.println(rev_number(number));
    }
}
  
// This code is contributed by talktoanmol.


Python3




# util functions
def number_length(num):
  
  # Return length of given number
    return len(str(num))
  
# reverse a given number
  
  
def rev_number(number):
    if (number % 10) == number:
        return number
  
    last = number % 10
    remaining = number // 10
    l = number_length(remaining)
  
    return last*pow(10, l) + rev_number(remaining)
  
  
def main():
    number = 123456
    print(rev_number(number))
  
  
# driver code
if __name__ == "__main__":
    main()
  
    # This code is contributed by talktoanmol


C#




// C# program to reverse a number
using System;
  
public class GFG {
  
    public static int length(int num)
    {
        // returns the length of a given number
        return (int)Math.Log10(num) + 1;
    }
  
    // reverse a given number
    static int rev_number(int num)
    {
        if ((num % 10) == num)
            return num;
        int last = num % 10;
        int remaining = num / 10;
        int l = length(remaining);
        return last * (int)Math.Pow(10, l)
            + rev_number(remaining);
    }
  
    // Driver code
    static public void Main()
    {
        int num = 123456;
        Console.Write(rev_number(num));
    }
}
  
// This Code is contributed by Susobhan Akhuli


Javascript




<script>
// Javascript program to reverse digits of a number
  
// Function to reverse digits of num
  
function length(number){
    // returns the length of a given number
    return ~~(Math.log10(number))+1;
}
  
// reverse a given number 
function rev_number(num){
    if ((num % 10) == num)
        return num;
    let last = ~~(num % 10);
    let remain = ~~(num / 10);
    let l = length(remain);
    return last * ~~(Math.pow(10, l)) + rev_number(remain);
}
  
  
let num = 123456;
// function call
document.write(rev_number(num));
      
// This code is contributed by Susobhan Akhuli
  
</script>


PHP




<?php
// PHP program to reverse digits of a number
  
// Function to reverse digits of num
function length($num){
    // returns the length of a given number
    return (int)(log10($num))+1;
}
  
// reverse a given number 
function rev_number($num){
    if (($num % 10) == $num)
        return $num;
    $last = ($num % 10);
    $remain = (int)($num / 10);
    $l = length($remain);
    return $last * (int)(pow(10, $l)) + rev_number($remain);
}
  
// Driver Code
$num = 123456;
// function call
echo rev_number($num);
  
// This code is contributed by Susobhan Akhuli
?>


Output

654321

 

Time Complexity: O(log10n) where n is the given input number.
Auxiliary Space: O(log10n) for recursive stack space.

Using String in java

We will convert the number to a string using StringBuffer after this, we will reverse that string using the reverse() method 

corner case 

Input: 32100

So for the above input if we try to solve this by reversing the string, then the output will be 00123.

So to deal with this situation we again need to convert the string to integer so that our output will be 123

C




// C program to reverse a number
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
  
// reverse string function
void reverse(char* begin, char* end)
{
    char temp;
    while (begin < end) {
        temp = *begin;
        *begin++ = *end;
        *end-- = temp;
    }
}
  
// Function to reverse words
void reverseWords(char* s)
{
    char* word_begin = s;
  
    // Word boundary
    char* temp = s;
  
    // Reversing individual words as
    // explained in the first step
    while (*temp) {
        temp++;
        if (*temp == '\0') {
            reverse(word_begin, temp - 1);
        }
        else if (*temp == ' ') {
            reverse(word_begin, temp - 1);
            word_begin = temp + 1;
        }
    }
  
    // Reverse the entire string
    reverse(s, temp - 1);
}
  
int reverseDigits(int num)
{
    char strin[100];
    // converting number to string
    sprintf(strin, "%d", num);
  
    // reversing the string
    reverseWords(strin);
  
    // converting string to integer
    num = atoi(strin);
  
    // returning integer
    return num;
}
  
int main()
{
    int num = 123456;
    printf("Reverse of no. is %d", reverseDigits(num));
    return 0;
}
  
// This Code is contributed by Susobhan Akhuli


C++




// C++ program to reverse a number
#include <bits/stdc++.h>
using namespace std;
  
int reverseDigits(int num)
{
    // converting number to string
    string strin = to_string(num);
  
    // reversing the string
    reverse(strin.begin(), strin.end());
  
    // converting string to integer
    num = stoi(strin);
  
    // returning integer
    return num;
}
int main()
{
    int num = 4562;
    cout << "Reverse of no. is " << reverseDigits(num);
    return 0;
}
  
// This Code is contributed by ShubhamSingh10


Java




// Java program to reverse a number
  
public class GFG {
    static int reversDigits(int num)
    {
        // converting number to string
        StringBuffer string
            = new StringBuffer(String.valueOf(num));
  
        // reversing the string
        string.reverse();
  
        // converting string to integer
        num = Integer.parseInt(String.valueOf(string));
  
        // returning integer
        return num;
    }
    public static void main(String[] args)
    {
        int num = 4562;
        System.out.println("Reverse of no. is "
                           + reversDigits(num));
    }
}


Python3




# Python 3 program to reverse a number
  
  
def reversDigits(num):
  
    # converting number to string
    string = str(num)
  
    # reversing the string
    string = list(string)
    string.reverse()
    string = ''.join(string)
  
    # converting string to integer
    num = int(string)
  
    # returning integer
    return num
  
  
# Driver code
if __name__ == "__main__":
  
    num = 4562
    print("Reverse of no. is ", reversDigits(num))
  
    # This code is contributed by ukasp.


C#




// C# program to reverse a number
using System;
  
public class GFG {
  
    public static string ReverseString(string s)
    {
        char[] array = s.ToCharArray();
        Array.Reverse(array);
        return new string(array);
    }
  
    static int reversDigits(int num)
    {
        // converting number to string
        string strin = num.ToString();
  
        // reversing the string
        strin = ReverseString(strin);
  
        // converting string to integer
        num = int.Parse(strin);
  
        // returning integer
        return num;
    }
  
    // Driver code
    static public void Main()
    {
        int num = 4562;
        Console.Write("Reverse of no. is "
                      + reversDigits(num));
    }
}
  
// This Code is contributed by ShubhamSingh10


Javascript




<script>
  
// Javascript program to reverse a number
  
    function reversDigits(num)
    {
        // converting number to string
        let str
            = num.toString().split("").reverse().join("");
          
  
        // converting string to integer
        num = parseInt(str);
  
  
        // returning integer
        return str;
    }
  
// Driver Code
      
    let num = 4562;
    document.write("Reverse of no. is "
                           + reversDigits(num));
  
</script>


PHP




<?php
  
// PHP program to reverse a number
  
function reverseDigits($num)
{
    // converting number to string
    $strin = strval($num);
  
    // reversing the string
    $strin = strrev($strin);
  
    // converting string to integer
    $num = (int)($strin);
  
    // returning integer
    return $num;
}
  
$num = 123456;
echo "Reverse of no. is ". reverseDigits($num);
  
// This Code is contributed by Susobhan Akhuli
?>


Output

Reverse of no. is 123456

Time Complexity: O(log10n) where n is the input number
Auxiliary Space: O(1)

Reverse digits of an integer with overflow handled

Note that the above program doesn’t consider leading zeroes. For example, for 100 programs will print 1. If you want to print 001 then see this comment from Maheshwar.

Using Slicing in Python:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
int reverseDigits(int num)
{
  
    // converting number to string
    string str = to_string(num);
  
    // reversing the string
    reverse(str.begin(), str.end());
  
    // converting string to integer
    num = stoll(str);
  
    // returning integer
    return num;
}
  
// Driver Code
int main()
{
    int num = 4562;
    cout << "Reverse of no. is " << reverseDigits(num);
  
    return 0;
}
  
// This code is contributed by sanjoy_62.


Java




// Java program for the above approach
  
import java.util.*;
  
class GFG {
  
    static int reversDigits(int num)
    {
  
        // converting number to string
        String str = String.valueOf(num);
  
        // reversing the string
        str = new StringBuilder(str).reverse().toString();
  
        // converting string to integer
        num = Integer.valueOf(str);
  
        // returning integer
        return num;
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        int num = 4562;
        System.out.println("Reverse of no. is "
                           + reversDigits(num));
    }
}
  
// This code is contributed by phasing17


Python3




# Python 3 program to reverse a number
  
  
def reversDigits(num):
  
    # converting number to string
    string = str(num)
  
    # reversing the string
    string = string[::-1]
  
    # converting string to integer
    num = int(string)
  
    # returning integer
    return num
  
  
# Driver code
if __name__ == "__main__":
  
    num = 4562
    print("Reverse of no. is ", reversDigits(num))
  
    # This code is contributed by Susobhan Akhuli


C#




// C# program for the above approach
using System;
class GFG {
  
    static int reversDigits(int num)
    {
  
        // converting number to string
        string str = Convert.ToString(num);
  
        // reversing the string
        char[] charArray = str.ToCharArray();
        Array.Reverse(charArray);
        str = new string(charArray);
  
        // converting string to integer
        num = Convert.ToInt32(str);
  
        // returning integer
        return num;
    }
  
    // Driver Code
    public static void Main(string[] args)
    {
        int num = 4562;
        Console.Write("Reverse of no. is "
                      + reversDigits(num));
    }
}
  
// This code is contributed by phasing17


Javascript




// JavaScript program for the above approach
  
function reversDigits(num){
  
  // converting number to string
  let str = num.toString().split("");
  
  // reversing the string
  str.reverse();
    
  
  // converting string to integer
  num = parseInt(str.join(""))
  
  // returning integer
  return num;
}
  
// Driver Code
let num = 4562;
console.log("Reverse of no. is " + reversDigits(num));
  
  
// This code is contributed by phasing17


Output

Reverse of no. is 2654

Time Complexity: O(n), where n is the input number
Auxiliary Space: O(1)

Try extensions of above functions that should also work for floating-point numbers.

Divide and Conquer:

Algorithm:

Input: n
(1) Initialize rev1=0, rev2=0
(2) Compute no of digits in given input n and store it in size variable.
(3) Divide the number n into two parts i.e first_half and second_half.
(4) Loop for i in range(mid):
    (a) Remainder of first_half by 10 add it to the multiplication of 10 and rev1.
             rem=first_half%10
             rev1=10*rev1+rem
    (b) Remainder of second_half by 10 add it to the multiplication of 10 and rev2.
             rem=second_half%10
             rev2=10*rev2+rem
    (c) Divide first_half and second_half with 10.
             first_half=first_half//10
             second_half=second_half//10
 (5)if size is even.
             return rev2*10**mid+rev1
    otherwise 
             return (rev2*10**mid+rev1)*10+first_half

C++




#include<iostream>
#include<cmath>
using namespace std;
int main()
{
    long int n,first_half,second_half,rem,rev1,rev2,size,mid;
    n=1234;
    rev1=0,rev2=0;
  
//Find no of digits in number store it in size and divide size into two parts.
    size=floor(log10(n)+1);
    mid=size/2;
  
//Divide the given number in to two parts.
    first_half=n/pow(10,mid);
    second_half=n%(long int)(pow(10,mid)+0.5);
  
//Iterate the loop upto half no of digits in number.
    for(int i=0; i<mid; i++)
    {
//Reverse the First half digits and second half digits concurrently
        rem=first_half%10;
        rev1=10*rev1+rem;
        rem=second_half%10;
        rev2=10*rev2+rem;
        first_half=first_half/10;
        second_half=second_half/10;
    }
cout<<"Original no: "<<n<<endl;
//Concate Last half with First Half
    if(size%2==0)
    {
        cout<<"Reversed no: "<<rev2*(long int)(pow(10,mid)+0.5)+rev1;
    }
    else{
        cout<<"Reversed no: "<<(rev2*(long int)(pow(10,mid)+0.5)+rev1)*10+first_half;
    }
    return 0;
}
  
//This code contributed by SR.DHANUSH


Java




import java.lang.Math;
class Main
{
    public static void main (String[] args) 
    {
    int n,first_half,second_half,rem,rev1=0,rev2=0,size,mid;
    n=1234;
//Find no of digits in number store it in size and divide size into two parts.
    size=(int) Math.log10(n)+1;
    mid=(int) size/2;
  
//Divide the given number in to two parts.
    first_half=(int) (n/Math.pow(10,mid));
    second_half=n%(int) (Math.pow(10,mid));   
      
//Iterate the loop upto half no of digits in number.
    for(int i=0; i<mid; i++)
    {
//Reverse the First half digits and second half digits concurrently
        rem=first_half%10;
        rev1=10*rev1+rem;
        rem=second_half%10;
        rev2=10*rev2+rem;
        first_half=first_half/10;
        second_half=second_half/10;
    }
System.out.println("Original no: "+n);
//Concate Last half with First Half
    if(size%2==0)
    {
        System.out.println("Reversed no: "+(rev2*(int)(Math.pow(10,mid))+rev1));
    }
    else{
        System.out.println("Reversed no: "+((rev2*(int)(Math.pow(10,mid)+0.5)+rev1)*10+first_half));
    }
//This code contributed by SR.DHANUSH
}
}


Python3




# Python program to reverse a number.
import math
n = 1234
rev1 = 0
rev2 = 0
  
# Find no of digits in number store it in size and divide size into two parts.
size = int(math.log10(n))+1
mid = size//2
  
# Divide the given number in to two parts.
first_half = n//10**mid
second_half = n % 10**mid
  
# Iterate the loop upto half no of digits in number.
for i in range(mid):
# Reverse the First half digits and second half digits concurrently
    rem = first_half % 10
    rev1 = 10*rev1+rem
    rem = second_half % 10
    rev2 = 10*rev2+rem
    first_half = first_half//10
    second_half = second_half//10
      
# Concate Last half with First Half
print('Original no:', n)
if(size % 2 == 0):
    print('Reversed no:', rev2*10**mid+rev1)
else:
    print('Reversed no:', (rev2*10**mid+rev1)*10+first_half)
      
#This code contributed by SR DHANUSH


C#




// C# program to reverse a number.
using System;
  
class Program
{
    static void Main(string[] args)
    {
        int first_Half, second_Half, rem, rev1 = 0, rev2 = 0, size, mid;
        int n = 1234;
        //Find no of digits in number store it in size and divide size into two parts.
        size = (int)Math.Log10(n) + 1;
        mid = size / 2;
          
        //Divide the given number in to two parts.
        first_Half = (int)(n / Math.Pow(10, mid));
        second_Half = n % (int)(Math.Pow(10, mid));
          
        //Iterate the loop upto half no of digits in number.
        for (int i = 0; i < mid; i++)
        {
            //Reverse the First half digits and second half digits concurrently
            rem = first_Half % 10;
            rev1 = 10 * rev1 + rem;
            rem = second_Half % 10;
            rev2 = 10 * rev2 + rem;
            first_Half /= 10;
            second_Half /= 10;
        }
  
        Console.WriteLine("Original no: " + n);
          
        //Concate Last half with First Half
        if (size % 2 == 0)
        {
            Console.WriteLine("Reversed no: " + (rev2 * (int)(Math.Pow(10, mid)) + rev1));
        }
        else
        {
            Console.WriteLine("Reversed no: " + ((rev2 * (int)(Math.Pow(10, mid) + 0.5) + rev1) * 10 + first_Half));
        }
    }
}
  
// This code is contributed by Aman Kumar


Javascript




// JS code to implement the approach
  
// Find the number of digits in the number and divide it in
// half
let n = 1234;
let rev1 = 0;
let rev2 = 0;
let size = Math.floor(Math.log10(n)) + 1;
let mid = Math.floor(size / 2);
  
// Divide the number into two parts
let firstHalf = Math.floor(n / 10 ** mid);
let secondHalf = n % 10 ** mid;
  
// Reverse the first half and second half digits
// concurrently
for (let i = 0; i < mid; i++) {
    let rem = firstHalf % 10;
    rev1 = rev1 * 10 + rem;
    let rem2 = secondHalf % 10;
    rev2 = rev2 * 10 + rem2;
    firstHalf = Math.floor(firstHalf / 10);
    secondHalf = Math.floor(secondHalf / 10);
}
  
// Concatenate the last half with the first half
console.log("Original no:", n);
if (size % 2 == 0) {
    console.log("Reversed no:", rev2 * 10 ** mid + rev1);
}
else {
    console.log("Reversed no:",
                (rev2 * 10 ** mid + rev1) * 10 + firstHalf);
}
  
// This code is contributed by phasing17


Output

Original no: 1234
Reversed no: 4321

Time Complexity: O(log10(half no of digits in number)), the number indicates given input.
Auxiliary Space: O(1).

using divide and conquer:

We will divide the given number into two parts after this, reverse the first half and second half and join them.



Similar Reads

Write an Efficient C Program to Reverse Bits of a Number
Given an unsigned integer, reverse all bits of it and return the number with reversed bits. Input : n = 1Output : 2147483648 Explanation : On a machine with size of unsigned bit as 32. Reverse of 0....001 is 100....0. Input : n = 2147483648Output : 1 Recommended PracticeReverse BitsTry It!Method1 - Simple: Loop through all the bits of an integer. I
6 min read
Numbers of Length N having digits A and B and whose sum of digits contain only digits A and B
Given three positive integers N, A, and B. The task is to count the numbers of length N containing only digits A and B and whose sum of digits also contains the digits A and B only. Print the answer modulo 109 + 7.Examples: Input: N = 3, A = 1, B = 3 Output: 1 Possible numbers of length 3 are 113, 131, 111, 333, 311, 331 and so on... But only 111 i
15 min read
Minimum digits to be removed to make either all digits or alternating digits same
Given a numeric string str, the task is to find the minimum number of digits to be removed from the string such that it satisfies either of the below conditions: All the elements of the string are the same.All the elements at even position are same and all the elements at the odd position are same, which means the string is alternating with the equ
7 min read
Count of integers in a range which have even number of odd digits and odd number of even digits
Given a range [L, R], the task is to count the numbers which have even number of odd digits and odd number of even digits. For example, 8 has 1 even digit and 0 odd digit - Satisfies the condition since 1 is odd and 0 is even.545 has 1 even digit and 2 odd digits - Satisfies the condition since 1 is odd and 2 is even.4834 has 3 even digits and 1 od
11 min read
Find smallest number with given number of digits and sum of digits under given constraints
Given two integers S and D, the task is to find the number having D number of digits and the sum of its digits as S such that the difference between the maximum and the minimum digit in the number is as minimum as possible. If multiple such numbers are possible, print the smallest number.Examples: Input: S = 25, D = 4 Output: 6667 The difference be
7 min read
Number formed by deleting digits such that sum of the digits becomes even and the number odd
Given a non-negative number N, the task is to convert the number by deleting some digits of the number, such that the sum of the digits becomes even but the number is odd. In case there is no possible number, then print -1.Note: There can be multiple numbers possible for a given N.Examples: Input: N = 18720 Output: 17 Explanation: After Deleting 8,
5 min read
Find second smallest number from sum of digits and number of digits
Given the sum of digits as S and the number of digits as D, the task is to find the second smallest number Examples: Input: S = 9, D = 2Output: 27Explanation: 18 is the smallest number possible with sum = 9 and total digits = 2, Whereas the second smallest is 27. Input: S = 16, D = 3Output: 178Explanation: 169 is the smallest number possible with s
8 min read
Number of digits in the nth number made of given four digits
Find the number of digits in the nth number constructed by using 6, 1, 4, and 9 as the only digits in the ascending order. First few numbers constructed by using only 6, 1, 4, and 9 as digits in ascending order would be: 1, 6, 4, 9, 11, 14, 16, 19, 41, 44, 46, 49, 61, 64, 66, 69, 91, 94, 96, 99, 111, 114, 116, 119 and so on. Examples: Input : 6Outp
13 min read
Find smallest number with given number of digits and sum of digits
How to find the smallest number with given digit sum s and number of digits d? Examples : Input : s = 9, d = 2 Output : 18 There are many other possible numbers like 45, 54, 90, etc with sum of digits as 9 and number of digits as 2. The smallest of them is 18. Input : s = 20, d = 3 Output : 299 Recommended PracticeSmallest numberTry It! A Simple So
9 min read
Find the Largest number with given number of digits and sum of digits
Given an integer s and d, The task is to find the largest number with given digit sum s and the number of digits d. Examples: Input: s = 9, d = 2Output: 90 Input: s = 20, d = 3Output: 992 Recommended PracticeLargest number possibleTry It! Naive Approach: Consider all m digit numbers and keep a max variable to store the maximum number with m digits
13 min read
Count of unique pairs (i, j) in an array such that sum of A[i] and reverse of A[j] is equal to sum of reverse of A[i] and A[j]
Given an array arr[] consisting of N positive integers, the task is to find the count of unique pairs (i, j) such that the sum of arr[i] and the reverse(arr[j]) is the same as the sum of reverse(arr[i]) and arr[j]. Examples: Input: arr[] = {2, 15, 11, 7}Output: 3Explanation:The pairs are (0, 2), (0, 3) and (2, 3). (0, 2): arr[0] + reverse(arr[2]) (
7 min read
Count of numbers between range having only non-zero digits whose sum of digits is N and number is divisible by M
Given a range [L, R] and two positive integers N and M. The task is to count the numbers in the range containing only non-zero digits whose sum of digits is equal to N and the number is divisible by M.Examples: Input: L = 1, R = 100, N = 8, M = 2 Output: 4 Only 8, 26, 44 and 62 are valid numbers Input: L = 1, R = 200, N = 4, M = 11 Output: 2 Only 2
14 min read
Maximize the given number by replacing a segment of digits with the alternate digits given
Given many N digits. We are also given 10 numbers which represents the alternate number for all the one-digit numbers from 0 to 9. We can replace any digit in N with the given alternate digit to it, but we are only allowed to replace any consecutive segment of numbers for once only, the task is to replace any consecutive segment of numbers such tha
6 min read
Check if the sum of digits of number is divisible by all of its digits
Given an integer N, the task is to check whether the sum of digits of the given number is divisible by all of its digits or not. If divisible then print Yes else print No. Examples: Input: N = 12 Output: No Sum of digits = 1 + 2 = 3 3 is divisible by 1 but not 2. Input: N = 123 Output: Yes Approach: First find the sum of the digits of the number th
14 min read
Smallest positive number made up of non-repeating digits whose sum of digits is N
Given a positive integer N, the task is to find the smallest positive number made up of distinct digits having sum of its digits equal to N. If no such number exists, print "-1". Examples: Input: N = 11Output: 29Explanation: The sum of the digits = 2 + 9 = 11 ( = N). Input: N = 46Output: -1 Approach: The idea is based on the following observations:
6 min read
Find smallest number with given digits and sum of digits
Given two positive integers P and Q, find the minimum integer containing only digits P and Q such that the sum of the digits of the integer is N. Example: Input: N = 11, P = 4, Q = 7 Output: 47Explanation: There are two possible integers that can be formed from 4 and 7 such that their sum is 11 i.e. 47 and 74. Since we need to find the minimum poss
9 min read
Count number of integers in given range with adjacent digits different and sum of digits equal to M
Given integers T, A, and B, the task for this problem is to find numbers in the range [A, B] such that the adjacent digits of the number are different and the sum of digits is equal to T. ( A ? B ? 1018) Examples: Input: T = 5, A = 1, B = 100Output: 6Explanation: 5, 14, 23, 32, 41, and 50 are valid integers that are in between the range 1 to 100 an
15+ min read
Check whether product of digits at even places is divisible by sum of digits at odd place of a number
Given a number N and numbers of digits in N, the task is to check whether the product of digits at even places of a number is divisible by sum of digits at odd place. If it is divisible, output "TRUE" otherwise output "FALSE". Examples: Input: N = 2157 Output: TRUESince, 1 * 7 = 7, which is divisible by 2+5=7Input: N = 1234Output: TRUESince, 2 * 4
13 min read
Find the average of k digits from the beginning and l digits from the end of the given number
Given three integers N, K and L. The task is to find the average of the first K digits and the last L digits of the given number N without any digit overlapping.Examples: Input: N = 123456, K = 2, L = 3 Output: 3.0 Sum of first K digits will be 1 + 2 = 3 Sum of last L digits will be 4 + 5 + 6 = 15 Average = (3 + 15) / (2 + 3) = 18 / 5 = 3Input: N =
13 min read
Smallest number with given sum of digits and sum of square of digits
Given the sum of digits a and sum of the square of digits b . Find the smallest number with the given sum of digits and the sum of the square of digits. The number should not contain more than 100 digits. Print -1 if no such number exists or if the number of digits is more than 100.Examples: Input : a = 18, b = 162 Output : 99 Explanation : 99 is t
15+ min read
Reverse digits of an integer with overflow handled | Set 2
Given a 32-bit integer N. The task is to reverse N, if the reversed integer overflows, print -1 as the output. Examples Input: N = 123Output: 321 Input: N = -123Output: -321 Input: N = 120Output: 21 Approach: Unlike approaches Set 1 of the article, this problem can be solved simply by using a 64-bit data structure and range of int data type [-2^31,
9 min read
Reverse digits of an integer with overflow handled
Write a program to reverse an integer assuming that the input is a 32-bit integer. If the reversed integer overflows, print -1 as the output. Let us see a simple approach to reverse digits of an integer. [GFGTABS] C++ // A simple C program to reverse digits of // an integer. #include <bits/stdc++.h> using namespace std; int reversDigits(int n
15 min read
Check if sum of digits in the left half is divisible by sum of digits in the right half in the largest permutation of N
Given a positive integer N, the task is to maximize the integer N by rearranging the digits and check if the sum of the left half digits is divisible by the sum of the right half digits or not. If found to be true, then print "Yes". Otherwise, print "No". If the number of digits(say D) in the given number N is odd, then consider any of the two poss
8 min read
Count N-digit numbers whose digits does not exceed absolute difference of the two previous digits
Given an integer N, the task is to count the number of N-digit numbers such that each digit, except the first and second digits, is less than or equal to the absolute difference of the previous two digits. Examples: Input: N = 1Output: 10Explanation: All the numbers from [0 - 9] are valid because the number of digits is 1. Input : N = 3Output : 375
9 min read
Numbers with sum of digits equal to the sum of digits of its all prime factor
Given a range, the task is to find the count of the numbers in the given range such that the sum of its digit is equal to the sum of all its prime factors digits sum.Examples: Input: l = 2, r = 10 Output: 5 2, 3, 4, 5 and 7 are such numbers Input: l = 15, r = 22 Output: 3 17, 19 and 22 are such numbers As, 17 and 19 are already prime. Prime Factors
13 min read
Maximize the value of A by replacing some of its digits with digits of B
Given two string A and B which represents two integers, the task is to print the maximized value of A after replacing 0 or more digits of A with any digit of B. Note: A digit in B can only be used once. Examples: Input: A = "1234", B = "4321" Output: 4334 1 can be replaced with 4 and 2 can be replaced with 3. Input: A = "1002", B = "100" Output: 11
5 min read
Count numbers in given range such that sum of even digits is greater than sum of odd digits
Given two integers L and R denoting a range [L, R]. The task is to find the total count of numbers in the given range [L,R] whose sum of even digits is greater than the sum of odd digits. Examples: Input : L=2 R=10 Output : 4 Numbers having the property that sum of even digits is greater than sum of odd digits are: 2, 4, 6, 8 Input : L=2 R=17 Outpu
14 min read
Count of numbers upto N digits formed using digits 0 to K-1 without any adjacent 0s
Given two integers N and K, the task is to count the numbers up to N digits such that no two zeros are adjacents and the range of digits are from 0 to K-1.Examples: Input: N = 2, K = 3 Output: 8 Explanation: There are 8 such numbers such that digits are from 0 to 2 only, without any adjacent 0s: {1, 2, 10, 11, 12, 20, 21, 22}Input: N = 3, K = 3 Out
12 min read
Count numbers from given range having odd digits at odd places and even digits at even places
Given two integers L and R, the task is to count numbers from the range [L, R] having odd digits at odd positions and even digits at even positions respectively. Examples: Input: L = 3, R = 25Output: 9Explanation: The numbers satisfying the conditions are 3, 5, 7, 9, 10, 12, 14, 16 and 18. Input: L = 128, R = 162Output: 7Explanation: The numbers sa
15+ min read
Count numbers from a given range that can be expressed as sum of digits raised to the power of count of digits
Given an array arr[] consisting of queries of the form {L, R}, the task for each query is to count the numbers in the range [L, R] that can be expressed as the sum of its digits raised to the power of count of digits. Examples: Input: arr[][] = {{8, 11}}Output: 2Explanation:From the given range [1, 9], the numbers that can be expressed as the sum o
10 min read