这是一个惬意的周六,又找到了一道小学数学通关题
2165. 重排数字的最小值
# @param {Integer} num
# @return {Integer}
def smallest_number(num)
if num >= 0
if num < 10
return num
end
n = num.to_s
h = Hash.new(0)
n.chars.each do |n1|
h[n1] += 1
end
m1 = h.keys.sort
x = ""
if m1[0] == "0"
x << m1[1]
x << m1[0]*h[m1[0]]
x << m1[1]*(h[m1[1]]-1)
for i in 2...m1.length
x << m1[i]*h[m1[i]]
end
return x.to_i
else
for i in 0...m1.length
x << m1[i]*h[m1[i]]
end
return x.to_i
end
else
n = num.to_s
h = Hash.new(0)
n.chars.each do |n1|
if n1 != "-"
h[n1] += 1
end
end
m1 = h.keys.sort.reverse
x = "-"
for i in 0...m1.length
x << m1[i]*h[m1[i]]
end
return x.to_i
end
end