Python Code to Generate k-digit Number With k As Each Digit

Published September 16, 2024

Python code snippet

This is part of a competitive programming problem.

Problem

You are given a integer variable k with any value between and including 1 and 9.

1 <= k <= 9

Your job is to create an integer variable n which is a k-digit number where all digits are k.

Example:

When k = 5, n = 55555

When k = 2, n = 22

When k = 9, n = 999999999

When k = 4, n = 4444

and so on.

Let us find different ways of generating n for k = 4.

Solution Using Strings

Using strings, we can type cast k to a string, clone it k times using the * operator and then type cast the result to an integer.

k = 4
n = int(str(k) * k)
print(n)

Output:

4444

Solution Using Lists

Using traditional lists, we create a loop that iterates k times and multiply the loop counter i with 10i

k = 4
n = 0
for i in range(k):
    n += 10 ** i
n *= k
print(n)

This way, n = k * (1000 + 100 + 10 + 1).

Output:

4444

This solution has the second best time complexity O(n). It can also be the slowest compared to the next two solutions.

Solution Using List Comprehension

Using list comprehension, we can condense the working part into a one-liner:

n = (k * sum([10 ** i for i in range(k)]))

The complete program would be:

k = 4
n = (k * sum([10 ** i for i in range(k)]))
print(n)

Output:

4444

This solution has the second best time complexity O(n). It is faster than the previous solution.

Solution Using Numeric Operations

To get a k-digit number with all k in it, we can use this algorithm.

  1. First, create a k-digit number with all 1.
  2. Multiply that number with k. That gives us the number we want.

To get a k-digit number with all 1, we can use this math expression:

(10k - 1) / 9

For example, if k = 4:

(104 - 1) / 9 = 1111

Now, multiply this result with k and we get :

1111 * 4 = 4444

The program would be:

k = 4
n = k * (10 ** k - 1) // 9
print(n)

We used floor division because int divided by int returns a float, and we want only the int part.

Output:

4444

This solution has the best time space complexity O(1) and is the fastest solution.

Conclusion

If you have another optimal way to do this, let me know in the comments. Thanks for reading.

Related Posts

If you have any questions, please contact me at arulbOsutkNiqlzziyties@gNqmaizl.bkcom. You can also post questions in our Facebook group. Thank you.

Disclaimer: Our website is supported by our users. We sometimes earn affiliate links when you click through the affiliate links on our website.

Last Updated: September 16, 2024.     This post was originally written on September 14, 2024.