Skip to content
CodeKruPro

Pad a number with leading zeros

Coding problemEasyAsked in: Accenture

Given a non-negative integer n and a width, return n written in decimal with zeros added on the left until the text is exactly width characters long.

If n already has width digits or more, return its digits unchanged. Test data often needs this, for example order numbers like "000042".

Examples

Example 1
Input: n = 42, width = 6
Output: "000042"
Example 2
Input: n = 12345, width = 3
Output: "12345"
The number is already wider than 3.
Example 3
Input: n = 0, width = 3
Output: "000"

Constraints

  • n is between 0 and 2,147,483,647
  • width is between 1 and 20

Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.

Run your code to see the results here.

This question is part of Pro+

Pro+ opens every question in Interview Prep and the mock interview. Every article and the first 2 questions of each topic stay free. Hands-on Selenium and API tasks follow their course lesson's own lock.

See Pro+

Already have Pro+? Sign in