简体   繁体   中英

Method to find number of digits after converting from a different base number

The text in quotes gives a bit of background on my program in case it's needed to understand my issue, you might be able to fully understand with the stuff at the end unquoted if you don't feel like reading it.

I'm working on the common project of sorting in C++, and I am currently doing radix sort. I have it as a function, taking in a vector of strings, an integer holding the max number of digits, and an integer with the radix/base of the numbers: (numbers, maxDigits, radix)

Since the program takes in numbers of different base and as a string, I'm using stoi to convert them to a base 10 integer to make the process easier to generalize. Here's a quick summary of the algorithm:

  • create 10 queues to hold values 0 to 9
  • iterate through each digit (maxDigit times)
    • iterate through each number in the vector (here it converts to a base 10)
    • put them into the queue based on the current digit it's looking at
    • pull the numbers out of the queues from beginning to end back into the vector

As for the problem I'm trying to wrap my head around, I want to change the maxDigit value (with whatever radix the user inputs) to a maxDigit value after it is converted to base 10. In other words, say the user used the code

radixSort(myVector, 8, 2)

to sort a vector of numbers with the max number of digits 8 and a radix of 2. Since I convert the radix of the number to 10, I'm trying to find an algorithm to also change the maxDigits, if that makes sense.

I've tried thinking about this so much, trying to figure out a simple way through trial and error. If I could get some tips or help in the right direction that would be a great help.

If something is in radix 2 and max digits 8, then its largest value is all ones. And 11111111 = 255, which is (2^8 - 1).

The maximum digits in base 10 will be whatever is needed to represent that largest value. Here we see that to be 3. Which is the base 10 logarithm of 255 (2.40654018043), rounded up to 3.

So basically just round up log10 (radix^maxdigits - 1) to the nearest whole number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM