[TS] Parse a string to an integer
string to an TS Integer parse
2023-09-14 09:00:51 时间
A common interview question is to write
a
function
that
converts
a
string
into
an
integer e.g. "123"
=> 123
.
This
function
is commonly
called
atoi
because
we
are
converting
an
ASCII
string
into
an
integer.
In this lesson we cover the proper way to do this in JavaScript which is parseInt
along with implementing it using basic ascii math.
Writing a function whichi convert string to number, to do that
1. Convert each "string" char to ASCII code by using
str.charCodeAt(index)
2. Each round, we should increase the acc value by *10
function atoi (str: string): number { const zeroCode = '0'.charCodeAt(0); console.log("zeroCode", zeroCode); let sub = 1; if(str[0] === '-') { sub = -1; str = str.substring(1); console.log("sub string", str); } return sub * str.split('') .reduce((acc, curr) => { acc = acc * 10 + (curr.charCodeAt(0) - zeroCode) return acc; }, 0) } console.log(atoi("123")); //123 console.log(atoi("-123")); //-123
import { atoi } from './atoi'; test('basic', () => { expect(atoi('123')).toBe(123); expect(atoi('-1123')).toBe(-1123); });
相关文章
- string length() 方法注意点
- PHP函数 mysql_real_escape_string 与 addslashes 的区别
- UVA 10739 String to Palindrome(动态规划 回文)
- int to string
- c++ string split function
- [TS] Parse a string to an integer
- [Javascript] String in Javascript
- C语言string.h中常用字符函数介绍
- svn error:“svn: Can’t convert string from ‘UTF-8′ to native encoding”错误记录
- C# POST 发送XML(返回string中可能出现中文乱码问题)
- svn error:“svn: Can’t convert string from ‘UTF-8′ to native encoding”错误记录
- 成功解决tensorflow.python.framework.errors_impl.UnimplementedError: Cast string to int32 is not supporte
- 成功解决tensorflow.python.framework.errors_impl.UnimplementedError: Cast string to int32 is not supporte
- 成功解决ValueError: could not convert string to float: ‘N‘
- 【报错解决】Python re模块 sub函数 :Error expected string or bytes-like object
- 浅谈String str = ““ 和 new String()的区别
- LINQ体验(11)——LINQ to SQL语句之Null语义和String/DateTime方法
- Java中的final变量 final修饰变量 final修饰方法 final修饰类 final和String的关系
- Mybatis Mapper.xml 需要查询返回List<String>
- 实战c++中的string系列--不要使用memset初始化string(一定别这么干)
- C++报错: ISO C++11 does not allow conversion from string literal to ‘char *‘(一百一三十五)
- LeetCodeOJ. String to Integer (atoi)