DEV Community

Shalom Steinmetz
Shalom Steinmetz

Posted on

Extracting Ones from an Integer Using the Modulo Operator

In this post, I'll discuss an uncommon use case for the modulo operator: extracting ones from an integer. Let's say we have a variable that is of type Integer and we we want to know how many ones there are. For example, the number 12 has 2 ones. How do we extract the ones digit? The inefficient way to do this would be to convert the integer to a string, grab the last character from the string, and then convert it back to an integer like this:

integer = 555

# Inefficient way - don't do this
ones_string = str(integer)[-1]
ones = int(ones_string)
Enter fullscreen mode Exit fullscreen mode

Fortunately, there's a more elegant and efficient solution. You can use the modulo operator to obtain the ones digit directly, as follows:

# Efficient way - do this
ones = integer % 10
Enter fullscreen mode Exit fullscreen mode

By taking the remainder when dividing the integer by 10, we effortlessly isolate the ones digit. This method not only simplifies the task but also improves code readability and performance.

Top comments (0)