-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Improve algorithm to count digits in Long #1548
Conversation
🎉 |
private val DigitCountToLargestValue = longArrayOf( | ||
-1, // Every value has more than 0 digits. | ||
9L, // For 1 digit (index 1), the largest value is 9. | ||
99L, | ||
999L, | ||
9999L, | ||
99999L, | ||
999999L, | ||
9999999L, | ||
99999999L, | ||
999999999L, | ||
9999999999L, | ||
99999999999L, | ||
999999999999L, | ||
9999999999999L, | ||
99999999999999L, | ||
999999999999999L, | ||
9999999999999999L, | ||
99999999999999999L, | ||
999999999999999999L, // For 18 digits (index 18), the largest value is 999999999999999999. | ||
Long.MAX_VALUE, // For 19 digits (index 19), the largest value is MAX_VALUE. | ||
) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is a slight deviation from the original table proposed in the article:
private val PowersOfTen = longArrayOf(
0,
10,
100,
1000,
10000,
100000,
1000000,
10000000,
100000000,
1000000000,
10000000000,
100000000000,
1000000000000,
10000000000000,
100000000000000,
1000000000000000,
10000000000000000,
100000000000000000,
1000000000000000000
)
@swankjesse & I discovered that the original table wouldn't work for the Long.MAX_VALUE
test case, as it has more digits than 10^18, and 10^19 is outside of the range of Long. The code instead compares against largest numbers that can be represented with a given digit count, which allowed us to fit another entry into the table!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I saw that and it's a great improvement!
The original code made it up into kotlinx.io. Do you want to send them a PR, too? |
Sure, done! Kotlin/kotlinx-io#413 |
Based on "Down Another Rabbit Hole" by @romainguy - thanks!