add: 实现string2int()函数

This commit is contained in:
yi-ge 2020-05-05 21:15:39 +08:00
parent a920efef27
commit 1227f993ae
3 changed files with 39 additions and 0 deletions

View File

@ -63,6 +63,10 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
- LeetCode 179. 最大数 https://leetcode-cn.com/problems/largest-number/
- LintCode 184. 最大数 https://www.lintcode.com/problem/largest-number/description
- [实现string2int()函数](src/string/string2int.js)
- 面试题参考思路,不严谨实现 廖雪峰 不要使用JavaScript内置的parseInt()函数利用map和reduce操作实现一个string2int()函数。 https://www.liaoxuefeng.com/wiki/1022910821149312/1024322552460832
## 数组
- [电话号码的字母组合](src/array/letter-combinations-of-a-phone-number.js)

13
src/string/string2int.js Normal file
View File

@ -0,0 +1,13 @@
// 注意,仅为提供面试思路,实现不严谨
export const string2int = (s) => {
// 如果是机器检查。这道题很简单,*1就完了, 或者Math.floor或者 +'123'。都可以绕开系统的检查。
// 但是如果是面试就必须要用到map和reduce上述方法显然不是面试官想听到的。
// 而这俩都是数组的方法因此首先用split('')将'123'变为['1','2','3']。
// reduce常规用法就是 total * 10 + currentValue。至于map需要思考如何用map将字符串数组变为数字数组。
// 某人问过我这道题,由于网上写的基本都是错的,面试可能通不过,特记录于此。
return s.split('').map(i => i.charCodeAt() - 48).reduce((total, currentValue) => total * 10 + currentValue)
// 温馨提示:面试不一定需要说出你知道的或者你的各种想法,而是要尽可能准确的回答面试官想知道的答案。
// 特别对于职业发展来说,如果你的真实想法不一定是面试官希望听到的,就不要说。
}

View File

@ -0,0 +1,22 @@
import { string2int } from '../../src/string/string2int'
test('实现string2int()函数', () => {
// 测试:
if (string2int('0') === 0 && string2int('12345') === 12345 && string2int('12300') === 12300) {
if (string2int.toString().indexOf('parseInt') !== -1) {
console.log('请勿使用parseInt()!')
} else if (string2int.toString().indexOf('Number') !== -1) {
console.log('请勿使用Number()!')
} else {
console.log('测试通过!')
}
} else {
console.log('测试失败!')
}
expect(string2int('123')).toBe(123)
expect(string2int('12300')).toBe(12300)
expect(string2int('0')).toBe(0)
// 注意,仅为提供面试思路,实现不严谨
})