Print all substring of a number without any conversion
Last Updated :
01 Sep, 2022
Given an integer N, the task is to print all the substring of N without doing any conversion i.e converting it into a string or an array.
Examples:
Input: N = 12345
Output: Possible Substrings: {1, 12, 123, 1234, 12345, 2, 23, 234, 2345, 3, 34, 345, 4, 45, 5}
Input: N = 123
Output: Possible Substrings: {1, 12, 123, 2, 23, 3}
Approach:
- Take the power of 10 according to size.
- Divide the number till it will become 0 and print.
- Then change the number to next the position of that number by taking the modulo with k.
- Update the no. of digits.
- Repeat the same process till n becomes 0.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void printSubstrings( int n)
{
int s = log10 (n);
int d = ( int )( pow (10, s) + 0.5);
int k = d;
while (n) {
while (d) {
cout << n / d << endl;
d = d / 10;
}
n = n % k;
k = k / 10;
d = k;
}
}
int main()
{
int n = 123;
printSubstrings(n);
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
static void printSubstrings( int n)
{
int s = ( int )Math.log10(n);
int d = ( int )(Math.pow( 10 , s) + 0.5 );
int k = d;
while (n > 0 )
{
while (d > 0 )
{
System.out.println(n / d);
d = d / 10 ;
}
n = n % k;
k = k / 10 ;
d = k;
}
}
public static void main(String args[])
{
int n = 123 ;
printSubstrings(n);
}
}
|
Python3
import math
def printSubstrings(n):
s = int (math.log10(n));
d = (math. pow ( 10 , s));
k = d;
while (n > 0 ):
while (d > 0 ):
print ( int (n / / d));
d = int (d / 10 );
n = int (n % k);
k = int (k / / 10 );
d = k;
if __name__ = = '__main__' :
n = 123 ;
printSubstrings(n);
|
C#
using System;
class GFG
{
static void printSubstrings( int n)
{
int s = ( int )Math.Log10(n);
int d = ( int )(Math.Pow(10, s) + 0.5);
int k = d;
while (n > 0)
{
while (d > 0)
{
Console.WriteLine(n / d);
d = d / 10;
}
n = n % k;
k = k / 10;
d = k;
}
}
public static void Main()
{
int n = 123;
printSubstrings(n);
}
}
|
PHP
<?php
function printSubstrings( $n )
{
$s = (int)log10( $n );
$d = (int)(pow(10, $s ) + 0.5);
$k = $d ;
while ( $n )
{
while ( $d )
{
echo (int)( $n / $d ) . "\n" ;
$d = (int)( $d / 10);
}
$n = $n % $k ;
$k = (int)( $k / 10);
$d = $k ;
}
}
$n = 123;
printSubstrings( $n );
?>
|
Javascript
<script>
function printSubstrings(n)
{
var s = parseInt(Math.log10(n));
var d = parseInt((Math.pow(10, s) + 0.5));
var k = d;
while (n > 0)
{
while (d > 0)
{
document.write(parseInt(n / d)+ "<br>" );
d = parseInt(d / 10);
}
n = n % k;
k = parseInt(k / 10);
d = k;
}
}
var n = 123;
printSubstrings(n);
</script>
|
Time Complexity: O(nlogn)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...