07. Nth Natural Number
The problem can be found at the following link: Question Link
Note: Sorry for uploading late, my exam is going on.
Problem Description
Given a positive integer n, find the nth natural number after removing all the numbers that contain the digit 9.
Examples:
Input:
n = 8Output:
8Explanation: The first 8 natural numbers without the digit 9 are: 1, 2, 3, 4, 5, 6, 7, 8. Hence, the 8th number is 8.
My Approach
Base-9 Representation:
The key idea is to map the natural numbers that exclude the digit
9onto a base-9 number system.Numbers in base 10 that contain the digit
9can be "removed" by converting the indexnto a number in base-9.
Step-by-Step Process:
Convert the given
ninto a number in base-9. This ensures that the number does not contain the digit9, as base-9 numbers inherently do not have a digit9.For example, the number
9in base-10 maps to10in base-9, skipping the digit9.
Conversion Algorithm:
Initialize
base9numas0andposas1to keep track of the current place value.Repeatedly extract the remainder when
nis divided by9, multiply it by the current place value, and add it tobase9num.Divide
nby9to shift to the next place in the base-9 number, and update the position multiplier (pos).
Final Answer:
After processing all digits of
n, the resulting number in base-9 is thenth natural number after removing all numbers containing the digit9.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(log₉n), as the algorithm repeatedly divides the number by
9in each step, taking logarithmic time in base 9.Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for storing variables like
base9numandpos.
Code (C++)
class Solution {
public:
long long findNth(long long n) {
long long base9num = 0;
long long pos = 1;
while (n > 0) {
base9num += (n % 9) * pos;
n /= 9;
pos *= 10;
}
return base9num;
}
};Code (Java)
class Solution {
long findNth(long n) {
long base9num = 0;
long pos = 1;
while (n > 0) {
base9num += (n % 9) * pos;
n /= 9;
pos *= 10;
}
return base9num;
}
}Code (Python)
class Solution:
def findNth(self, n):
base9num = 0
pos = 1
while n > 0:
base9num += (n % 9) * pos
n //= 9
pos *= 10
return base9numContribution and Support
For discussions, questions, or doubts related to this solution, please visit my LinkedIn: Any Questions. Thank you for your input; together, we strive to create a space where learning is a collaborative endeavor.
⭐ Star this repository if you find it helpful or intriguing! ⭐
📍Visitor Count
Last updated