路漫漫其修远兮, 吾将上下而求索

0%

原生

直接使用数字的 toLocaleString 方法, 就可以实现数字每 3 位添加一个逗号了, 缺点是针对浮点数, 只保留小数点后三位数并进行了四舍五入.

1
2
3
function thousands(num){
return num.toLocaleString();
}

字符串硬干

1
2
3
4
5
6
7
8
9
10
11
12
const numToThousand = num => {
let stringNum = (num || 0).toString();
let result = '';
while (stringNum.length > 3) {
result = ',' + stringNum.slice(-3) + result;
stringNum = stringNum.slice(0, stringNum.length - 3);
}
if (stringNum) {
result = stringNum + result;
}
return result;
};

正则

1
2
3
4
5
6
7
function thousands(num){
const str = num.toString();
const reg = str.includes(".")
? /(\d)(?=(\d{3})+\.)/g
: /(\d)(?=(?:\d{3})+$)/g;
return str.replace(reg,"$1,");
}

字符串打散

1
2
3
4
5
6
7
8
9
10
11
function thousands(num){
var splits=[],res=[];
var splits = num.toString().split(".");
splits[0].split("").reverse().forEach(function(item,i){
if (i % 3 == 0 && i!=0) {
res.push(",");
}
res.push(item);
});
return res.reverse().join("")+(splits.length>1 ? "."+splits[1] : "");
}

题目描述

把一个数组最开始的若干个元素搬到数组的末尾, 我们称之为数组的旋转. 输入一个递增排序的数组的一个旋转, 输出旋转数组的最小元素. 例如, 数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转, 该数组的最小值为 1

示例 1:

1
2
输入:[3,4,5,1,2]
输出:1
阅读全文 »