Home >Backend Development >Python Tutorial >How can integers be converted into strings in arbitrary bases?

How can integers be converted into strings in arbitrary bases?

DDD
DDDOriginal
2024-12-13 18:25:10687browse

How can integers be converted into strings in arbitrary bases?

Conversion of Integers to Strings in Arbitrary Bases

This question seeks a method to convert integers into strings in any base. Unlike Python's int(str, base) function, which allows creation of integers from strings of a specified base, the desired approach is its inverse, whereby strings are constructed from integers.

A Simple Solution

Intuitively, people tended to focus on converting to small bases (e.g., less than the English alphabet's length). However, the question demands a universal solution applicable to any base from 2 to infinity.

A straightforward solution is presented below:

def numberToBase(n, b):
    if n == 0:
        return [0]
    digits = []
    while n:
        digits.append(int(n % b))
        n //= b
    return digits[::-1]

This function takes an integer n and a base b as inputs and returns a list of digits representing n in base b. It works by iteratively dividing n by b and collecting the remainders (i.e., digits) in a list. The list is then reversed to obtain the correct order of digits.

For example, to convert 67854**15 - 102 to base 577:

print(numberToBase(67854 ** 15 - 102, 577))

Output:

[4, 473, 131, 96, 431, 285, 524, 486, 28, 23, 16, 82, 292, 538, 149, 25, 41, 483, 100, 517, 131, 28, 0, 435, 197, 264, 455]

This result can be further converted into any other desired base.

Key Points

  • The simplicity of the solution lies in the realization that a number in a specific base can be represented by a list of digits where each digit represents a power of the base.
  • The function returns a list of digits to accommodate any base, even those larger than 36 (the alphabetic base in Python).
  • Understanding the concept of numbers in different bases is crucial for grasping the working of this method.

The above is the detailed content of How can integers be converted into strings in arbitrary bases?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn