Find the middle digit of a given Number
Last Updated :
20 Dec, 2022
Given a number N, the task is to find the middle digit of the given number N. If the number has two middle digits then print the first middle digit.
Examples:
Input: N = 12345
Output: 3
Input: N = 98562
Output: 5
Approach: The middle digit of any number N can be given by
The length(len) of the given Number can be calculated as
For example:
If N = 12345
len = (int)log10(12345) + 1 = 5
Therefore,
First half of N = N/105/2 = N/102 = 123
Therefore middle digit of N = last digit of First half of N = (First half of N) % 10 = 123 % 10 = 3
Below code is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int middleDigit( int n)
{
int digits = ( int ) log10 (n) + 1;
n = ( int )(n / pow (10, digits / 2))
% 10;
return n;
}
int main()
{
int N = 98562;
cout << middleDigit(N)
<< "\n" ;
return 0;
}
|
Java
import java.util.*;
import java.io.*;
class GFG{
static int middleDigit( int n)
{
int digits = ( int )Math.log10(n) + 1 ;
n = ( int )(n / Math.pow( 10 , digits / 2 )) % 10 ;
return n;
}
public static void main(String[] args)
{
int N = 98562 ;
System.out.println(middleDigit(N));
}
}
|
Python3
import math
def middleDigit(n):
digits = math.log10(n) + 1 ;
n = int ((n / / math. pow ( 10 , digits / / 2 ))) % 10 ;
return n;
N = 98562 ;
print (middleDigit(N))
|
C#
using System;
class GFG{
static int middleDigit( int n)
{
int digits = ( int )Math.Log10(n) + 1;
n = ( int )(n / Math.Pow(10, digits / 2)) % 10;
return n;
}
static void Main()
{
int N = 98562;
Console.WriteLine(middleDigit(N));
}
}
|
Javascript
<script>
function middleDigit(n)
{
let digits = parseInt(Math.log10(n) + 1);
n = parseInt(parseInt(n / Math.pow(10, parseInt(digits / 2))) % 10);
return n;
}
let N = 98562;
document.write(middleDigit(N));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...