Skip to the content

Split the thousands

Problem

"Is that twelve thousand or one million two hundred thousand?" the boatswain grumbles over the treasure ledger. So he stops getting lost, the captain wants every haul written down with commas.

Write a function that takes a whole number from 0 up and returns a string with its digits and a comma every three, counting from the right: 1234567 is written "1,234,567" and 45678 is written "45,678".

A number with three digits or fewer gets no comma: 999 stays "999" and 0 stays "0". A comma never goes at the start: 300000 is "300,000". And the zeros in each group are all written: 5007 is "5,007".

Examples

  • A million and change

    1234567 → "1,234,567"

  • Three digits

    999 → "999"

  • The first thousand

    1000 → "1,000"

  • Short group in front

    45678 → "45,678"

  • A huge haul

    250000000 → "250,000,000"

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def with_commas(n):
    pass

JavaScript

function withCommas(n) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. It is free and you do not need an account to start.

More O(log n) challenges

See all challenges →