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. Ctrl or Cmd + Enter runs; add Shift to submit.