From 1227f993ae1f1e8e70e785b8dc732e4255993e24 Mon Sep 17 00:00:00 2001 From: yige Date: Tue, 5 May 2020 21:15:39 +0800 Subject: [PATCH] =?UTF-8?q?add:=20=E5=AE=9E=E7=8E=B0string2int()=E5=87=BD?= =?UTF-8?q?=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 ++++ src/string/string2int.js | 13 +++++++++++++ test/string/string2int.test.js | 22 ++++++++++++++++++++++ 3 files changed, 39 insertions(+) create mode 100644 src/string/string2int.js create mode 100644 test/string/string2int.test.js diff --git a/README.md b/README.md index 17f3f43..07c1b10 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/src/string/string2int.js b/src/string/string2int.js new file mode 100644 index 0000000..560348d --- /dev/null +++ b/src/string/string2int.js @@ -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) + + // 温馨提示:面试不一定需要说出你知道的或者你的各种想法,而是要尽可能准确的回答面试官想知道的答案。 + // 特别对于职业发展来说,如果你的真实想法不一定是面试官希望听到的,就不要说。 +} diff --git a/test/string/string2int.test.js b/test/string/string2int.test.js new file mode 100644 index 0000000..04bbe19 --- /dev/null +++ b/test/string/string2int.test.js @@ -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) + + // 注意,仅为提供面试思路,实现不严谨 +})