# Optimizing Digit Counting for Kotlin Long Values

DevFeed: [Optimizing Digit Counting for Kotlin Long Values](<https://devfeed.tech/articles/down-another-rabbit-hole-25597.md>)

Original publisher: [Read original article](<https://www.romainguy.dev/posts/2024/down-another-rabbit-hole/>)

Author: Romain Guy

Published: 2024-05-27T00:00:00Z

Content type: article

Language: en

Sources: [Posts on Romain Guy](<https://devfeed.tech/sources/posts-on-romain-guy.md>)

Topics: [Code](<https://devfeed.tech/topics/code.md>), [Optimization](<https://devfeed.tech/topics/optimization.md>), [Kotlin](<https://devfeed.tech/topics/kotlin.md>)

Tags: [android](<https://devfeed.tech/tags/android.md>), [assembly](<https://devfeed.tech/tags/assembly.md>), [code](<https://devfeed.tech/tags/code.md>), [developer](<https://devfeed.tech/tags/developer.md>), [floating-point](<https://devfeed.tech/tags/floating-point.md>), [graphics](<https://devfeed.tech/tags/graphics.md>), [kotlin](<https://devfeed.tech/tags/kotlin.md>), [numbers](<https://devfeed.tech/tags/numbers.md>), [operator](<https://devfeed.tech/tags/operator.md>), [optimization](<https://devfeed.tech/tags/optimization.md>), [performance](<https://devfeed.tech/tags/performance.md>)

## AI overview

This article explores ways to count the decimal digits in positive Kotlin Long values without relying on floating-point log10, which cannot represent every Long value exactly. It compares a straightforward branching approach with a binary-search solution and reports faster execution for the latter on a Pixel 6.

## Source excerpt

Jake Wharton recently caused me to go down yet another silly optimization rabbit hole when he nonchalantly linked to a piece of code used to count the number of digits in a Long during a Slack conversation about Kotlin's lack of ternary operator. This of course triggered folks like Madis Pink and me to want to optimize it... Counting digits Link to heading The simplest way to count the number of digits would be to compute log10(n).toInt() + 1, where n is our input number. Unfortunately logarithmic functions like Kotlin's log10 are only defined for floating point numbers. If our input is an Int or a Long, we could first convert to Double and then call log10, but not all Long values can be stored in a Double (any value above 2^53), and we would have to special case 0. We must therefore find a different solution1.