Skip to content

Commit 5167c04

Browse files
authored
Create 2165-smallest-value-of-the-rearranged-number.js
1 parent eea1d96 commit 5167c04

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* @param {number} num
3+
* @return {number}
4+
*/
5+
var smallestNumber = function(num) {
6+
const minus = num < 0
7+
const nums = Math.abs(num)
8+
.toString()
9+
.split('')
10+
.map(_ => parseInt(_))
11+
.sort((a, b) => minus ? b-a : a-b);
12+
if(!minus && nums[0] === 0) {
13+
let i = 0
14+
while(nums[i] === 0 && i < nums.length-1) i++
15+
nums[0] = nums[i]
16+
nums[i] = 0
17+
}
18+
const answer = parseInt(nums.map(_ => _.toString()).join(''))
19+
return minus ? -answer : answer
20+
};

0 commit comments

Comments
 (0)