A string defining a valid number is given. Output all the base conversions of substrings of length ‘k’ from base ‘b’ to base 10.
Input : str = "12212", k = 3, b = 3. Output : 17 25 23 Explanation : All the substrings of length 'k' are : 122, 221, 212. Base conversion can be computed using the formula.
Method 1 (Simple)
A simple approach is to use simple base conversion technique. For a base b number str, its decimal equivalent is str*b0 + str*b1 + str*b2 + … + str[n-1]*bn-1
17 25 23
Time Complexity : O(n*k)
Method 2 (Using sliding window)
We can use Sliding Window technique to solve it in linear time. Every time we slide the window, we will subtract the weight of first element i.e. (element * pow(b, k-1) ). Now multiplying the previous sum with ‘b’ will increase weight of every element 3 times which is required. Also we will simply add the new element in window because its weight will be element * pow(b, 0).
Below is the implementation :
# Simple Python3 program to convert all
# substrings from decimal to given base.
import math as mt
def substringConversions(str1, k, b):
for i in range(0, len(str1) – k + 1):
# Saving subin sub
sub = str1[i:k + i]
# Evaluating decimal for current
# substring and printing it.
Sum = 0
counter = 0
for i in range(len(sub) – 1, -1, -1):
Sum = (Sum + ((ord(sub[i]) – ord(‘0’)) *
counter += 1
print(Sum, end = ” “)
# Driver code
str1 = “12212”
b = 3
k = 3
substringConversions(str1, b, k)
# This code is contributed by
# Mohit Kumar 29
17 25 23
Time Complexity: O(n)
This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Convert from any base to decimal and vice versa
- Number of substrings with odd decimal value in a binary string
- Counting even decimal value substrings in a binary string
- Convert a number into negative base representation
- Convert Binary fraction to Decimal
- Count all Prime Length Palindromic Substrings
- Count number of distinct substrings of a given length
- Convert decimal fraction to binary number
- Quickly convert Decimal to other bases in Python
- Find number of substrings of length k whose sum of ASCII value of characters is divisible by k
- Convert a number of length N such that it contains any one digit at least 'K' times
- Convert to a string that is repetition of a substring of k length
- Minimum length of the sub-string whose characters can be used to form a palindrome of length K
- Complement of a number with any base b
- Double Base Palindrome
Improved By : mohit kumar 29