Nth character in Concatenated Decimal String
Last Updated :
27 Mar, 2023
If all decimal numbers are concatenated in a string then we will get a string that looks like string P as shown below. We need to tell the Nth character of this string.
P = “12345678910111213141516171819202122232425262728293031….”
Examples:
N = 10 10th character is 1
N = 11 11th character is 0
N = 50 50th character is 3
N = 190 190th character is 1
We can solve this problem by breaking the string length-wise. We know that in decimal 9 numbers are of length 1, 90 numbers are of length 2, 900 numbers are of length 3 and so on, so we can skip these numbers according to the given N and can get the desired character.
Processing for N = 190 is explained below,
P[184..195] = “979899100101”
First getting length of number at N,
190 – 9 = 181 number length is more than 1
181 – 90*2 = 1 number length is more than 2
1 – 900*3 < 0 number length is 3
Now getting actual character at N,
1 character after maximum 2 length number(99) is, 1
Processing for N = 251 is explained below,
P[250..255] = “120121”
First getting length of number at N,
251 - 9 = 242 number length is more than 1
242 – 90*2 = 62 number length is more than 2
62 – 900*3 < 0 number length is 3
Now getting actual character at N,
62 characters after maximum 2 length number(99) is,
Ceil(62/3) = 21, 99 + 21 = 120
120 is the number at N, now getting actual digit,
62%3 = 2,
2nd digit of 120 is 2, so our answer will be 2 only.
Implementation:
C++
// C++ program to get Nth character in
// concatenated Decimal String
#include <bits/stdc++.h>
using namespace std;
// Utility method to get dth digit of number N
char getDigit(int N, int d)
{
string str;
stringstream ss;
ss << N;
ss >> str;
return str[d - 1];
}
// Method to return Nth character in concatenated
// decimal string
char getNthChar(int N)
{
// sum will store character escaped till now
int sum = 0, nine = 9;
// dist will store numbers escaped till now
int dist = 0, len;
// loop for number lengths
for (len = 1; ; len++)
{
// nine*len will be incremented characters
// and nine will be incremented numbers
sum += nine*len;
dist += nine;
if (sum >= N)
{
// restore variables to previous correct state
sum -= nine*len;
dist -= nine;
N -= sum;
break;
}
nine *= 10;
}
// get distance from last one digit less maximum
// number
int diff = ceil((double)N / len);
// d will store dth digit of current number
int d = N % len;
if (d == 0)
d = len;
// method will return dth numbered digit
// of (dist + diff) number
return getDigit(dist + diff, d);
}
// Driver code to test above methods
int main()
{
int N = 251;
cout << getNthChar(N) << endl;
return 0;
}
Java
// Java program to get Nth character in
// concatenated Decimal String
class GFG
{
// Utility method to get dth digit of number N
static char getDigit(int N, int d)
{
String str=Integer.toString(N);
return str.charAt(d - 1);
}
// Method to return Nth character in concatenated
// decimal string
static char getNthChar(int N)
{
// sum will store character escaped till now
int sum = 0, nine = 9;
// dist will store numbers escaped till now
int dist = 0, len;
// loop for number lengths
for (len = 1; ; len++)
{
// nine*len will be incremented characters
// and nine will be incremented numbers
sum += nine * len;
dist += nine;
if (sum >= N)
{
// restore variables to previous correct state
sum -= nine * len;
dist -= nine;
N -= sum;
break;
}
nine *= 10;
}
// get distance from last one digit
// less maximum number
int diff = (int)(Math.ceil((double)(N) / (double)(len)));
// d will store dth digit of current number
int d = N % len;
if (d == 0)
d = len;
// method will return dth numbered digit
// of (dist + diff) number
return getDigit(dist + diff, d);
}
// Driver code
public static void main (String[] args)
{
int N = 251;
System.out.println(getNthChar(N));
}
}
// This code is contributed by mits
Python3
# Python program to get Nth character in
# concatenated Decimal String
# Method to get dth digit of number N
def getDigit(N, d):
string = str(N)
return string[d-1];
# Method to return Nth character in concatenated
# decimal string
def getNthChar(N):
# sum will store character escaped till now
sum = 0
nine = 9
# dist will store numbers escaped till now
dist = 0
# loop for number lengths
for len in range(1,N):
# nine*len will be incremented characters
# and nine will be incremented numbers
sum += nine*len
dist += nine
if (sum >= N):
# restore variables to previous correct state
sum -= nine*len
dist -= nine
N -= sum
break
nine *= 10
# get distance from last one digit less maximum
# number
diff = (N // len) + 1
# d will store dth digit of current number
d = N % len
if (d == 0):
d = len
# method will return dth numbered digit
# of (dist + diff) number
return getDigit(dist + diff, d);
# Driver code to test above methods
N = 251
print (getNthChar(N))
# Contributed by Afzal_Saan
C#
// C# program to get Nth character in
// concatenated Decimal String
using System;
class GFG
{
// Utility method to get dth digit of number N
static char getDigit(int N, int d)
{
string str = Convert.ToString(N);
return str[d - 1];
}
// Method to return Nth character in
// concatenated decimal string
static char getNthChar(int N)
{
// sum will store character
// escaped till now
int sum = 0, nine = 9;
// dist will store numbers
// escaped till now
int dist = 0, len;
// loop for number lengths
for (len = 1; ; len++)
{
// nine*len will be incremented characters
// and nine will be incremented numbers
sum += nine * len;
dist += nine;
if (sum >= N)
{
// restore variables to previous
// correct state
sum -= nine * len;
dist -= nine;
N -= sum;
break;
}
nine *= 10;
}
// get distance from last one digit
// less maximum number
int diff = (int)(Math.Ceiling((double)(N) /
(double)(len)));
// d will store dth digit of
// current number
int d = N % len;
if (d == 0)
d = len;
// method will return dth numbered
// digit of (dist + diff) number
return getDigit(dist + diff, d);
}
// Driver code
static void Main()
{
int N = 251;
Console.WriteLine(getNthChar(N));
}
}
// This code is contributed by mits
PHP
<?php
// PHP program to get Nth character
// in concatenated Decimal String
// Method to get dth digit
// of number N
function getDigit($N, $d)
{
$string = strval($N);
return $string[$d - 1];
}
// Method to return Nth character
// in concatenated decimal string
function getNthChar($N)
{
// sum will store character
// escaped till now
$sum = 0;
$nine = 9;
// dist will store numbers
// escaped till now
$dist = 0;
// loop for number lengths
for($len = 1; $len < $N; $len++)
{
// nine*len will be incremented characters
// and nine will be incremented numbers
$sum += $nine * $len;
$dist += $nine;
if ($sum >= $N)
{
// restore variables to
// previous correct state
$sum -= $nine * $len;
$dist -= $nine;
$N -= $sum;
break;
}
$nine *= 10;
}
// get distance from last one
// digit less maximum number
$diff = ($N / $len) + 1;
// d will store dth digit
// of current number
$d = $N % $len;
if ($d == 0)
$d = $len;
// method will return dth numbered
// digit of (dist + diff) number
return getDigit($dist + $diff, $d);
}
// Driver code
$N = 251;
echo getNthChar($N);
// This code is contributed by mits
?>
JavaScript
<script>
// JavaScript program to get Nth
// character in concatenated
// Decimal String
// Utility method to get dth
// digit of number N
function getDigit(N, d)
{
let str = N.toString();
return str[d - 1];
}
// Method to return Nth character in
// concatenated decimal string
function getNthChar(N)
{
// Sum will store character
// escaped till now
let sum = 0, nine = 9;
// dist will store numbers
// escaped till now
let dist = 0, len;
// Loop for number lengths
for(len = 1; ; len++)
{
// nine*len will be incremented
// characters and nine will be
// incremented numbers
sum += nine * len;
dist += nine;
if (sum >= N)
{
// Restore variables to
// previous correct state
sum -= nine * len;
dist -= nine;
N -= sum;
break;
}
nine *= 10;
}
// Get distance from last one digit
// less maximum number
let diff = (Math.ceil((N) / (len)));
// d will store dth digit
// of current number
let d = N % len;
if (d == 0)
d = len;
// Method will return dth numbered digit
// of (dist + diff) number
return getDigit(dist + diff, d);
}
// Driver Code
let N = 251;
document.write(getNthChar(N));
// This code is contributed by code_hunt
</script>
Time Complexity: O(Log N), where N is the given integer.
Auxiliary Space: O(1), since no extra Space used.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem