当前位置: 首页 > 编程日记 > 正文

LeetCode实战:字符串转换整数 (atoi)

题目英文

Implement atoi which converts a string to an integer.

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned.

Note:

  • Only the space character ’ ’ is considered as whitespace character.
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31− 1]. If the numerical value is out of the range of representable values, INT_MAX (2^31 − 1) or INT_MIN (−2^31) is returned.

Example 1:

Input: "42"
Output: 42

Example 2:

Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
Then take as many numerical digits as possible, which gets 42.

Example 3:

Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

Example 4:

Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical 
digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:

Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
Thefore INT_MIN (231) is returned.

题目中文

请你来实现一个 atoi 函数,使其能将字符串转换成整数。

首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。

当我们寻找到的第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字组合起来,作为该整数的正负号;假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成整数。

该字符串除了有效的整数部分之后也可能会存在多余的字符,这些字符可以被忽略,它们对于函数不应该造成影响。

注意:假如该字符串中的第一个非空格字符不是一个有效整数字符、字符串为空或字符串仅包含空白字符时,则你的函数不需要进行转换。

在任何情况下,若函数不能进行有效的转换时,请返回 0。

说明

假设我们的环境只能存储 32 位大小的有符号整数,那么其数值范围为 [−2^31, 2^31− 1]。如果数值超过这个范围,请返回 INT_MAX (2^31− 1)INT_MIN (−2^31)

示例 1:

输入: "42"
输出: 42

示例 2:

输入: "   -42"
输出: -42
解释: 第一个非空白字符为 '-', 它是一个负号。
我们尽可能将负号与后面所有连续出现的数字组合起来,最后得到 -42

示例 3:

输入: "4193 with words"
输出: 4193
解释: 转换截止于数字 '3' ,因为它的下一个字符不为数字。

示例 4:

输入: "words and 987"
输出: 0
解释: 第一个非空字符是 'w', 但它不是数字或正、负号。
因此无法执行有效的转换。

示例 5:

输入: "-91283472332"
输出: -2147483648
解释: 数字 "-91283472332" 超过 32 位有符号整数范围。 
因此返回 INT_MIN (231)

示例 6:

输入: "  0000000000012345678"
输出: 12345678

示例 7:

输入: "20000000000000000000"
输出: 2147483647

算法实现

public class Solution {public int MyAtoi(string str) {str = str.Trim();if (string.IsNullOrEmpty(str))return 0;if (str[0] != '-' && str[0] != '+'){if (str[0] < '0' || str[0] > '9')return 0;}int negative = 1;long result = 0;Queue<int> q = new Queue<int>();for (int i = 0; i < str.Length; i++){if (str[i] == '-' && i == 0){negative = -1;continue;}if (str[i] == '+' && i == 0){continue;}if (str[i] < '0' || str[i] > '9'){break;}q.Enqueue(str[i] - '0');}while (q.Count != 0){int i = q.Dequeue();//去掉队列前端的零if (i == 0 && result == 0)continue;// 返回超过位数的数字if (negative == 1 && q.Count > 10){return int.MaxValue;}if (negative == -1 && q.Count > 10){return int.MinValue;}result += i * (long)Math.Pow(10, q.Count);if (negative == 1 && result > int.MaxValue){return int.MaxValue;}if (negative == -1 && result * -1 < int.MinValue){return int.MinValue;}}return (int)result * negative;        }
}

实验结果

  • 状态:通过
  • 1079 / 1079 个通过测试用例
  • 执行用时: 104 ms, 在所有 C# 提交中击败了 98.32% 的用户
  • 内存消耗: 24.3 MB, 在所有 C# 提交中击败了 24.45% 的用户

提交结果


相关图文

1. “数组”类算法

  • LeetCode实战:三数之和
  • LeetCode实战:求众数
  • LeetCode实战:缺失的第一个正数
  • LeetCode实战:快乐数
  • LeetCode实战:寻找两个有序数组的中位数

2. “链表”类算法

  • LeetCode实战:两数相加
  • LeetCode实战:删除链表的倒数第N个节点
  • LeetCode实战:合并两个有序链表
  • LeetCode实战:合并K个排序链表
  • LeetCode实战:两两交换链表中的节点
  • LeetCode实战:旋转链表
  • LeetCode实战:环形链表

3. “栈”类算法

  • LeetCode实战:有效的括号
  • LeetCode实战:最长有效括号
  • LeetCode实战:逆波兰表达式求值

4. “队列”类算法

  • LeetCode实战:设计循环双端队列
  • LeetCode实战:滑动窗口最大值

5. “递归”类算法

  • LeetCode实战:爬楼梯

6. “字符串”类算法

  • LeetCode实战:反转字符串
  • LeetCode实战:翻转字符串里的单词

7. “树”类算法

  • LeetCode实战:相同的树
  • LeetCode实战:对称二叉树
  • LeetCode实战:二叉树的最大深度
  • LeetCode实战:将有序数组转换为二叉搜索树

8. “哈希”类算法

  • LeetCode实战:两数之和

9. “搜索”类算法

  • LeetCode实战:搜索二维矩阵

10. “动态规划”类算法

  • LeetCode实战:最长回文子串

11. “数值分析”类算法

  • LeetCode实战:x 的平方根

相关文章:

[C#] enum 枚举

默认情况下&#xff0c;枚举第一个值是0&#xff0c; 可显式为枚举赋值。 可以定义枚举的基础类型&#xff0c;如enum E : short {}, sizeof(E) 2&#xff1b;默认情况下是int。 枚举的继承链&#xff1a;ValueType->Enum->enum 枚举类型和基础类型之间的转换都是显式的…

制作Windows Mobile程序安装包

使用Visual Studio 2005制作wm上的cab安装包 打开项目&#xff0c;解决方案中添加新项&#xff0c;添加"智能设置CAB项目"&#xff1b;或者在空VS中新建一个"智能设置CAB项目" 添加新项 左侧的Program Files文件夹&#xff0c;没用可以删除 添加项目主输出…

学Java需要下载什么软件?都有什么作用?

学习java并非大家想象中的那么简单&#xff0c;除了书本和老师面授&#xff0c;软件的使用也有很大的作用&#xff0c;接下来小编为大家分享的就是关于“学Java需要下载什么软件?都有什么作用?”的内容&#xff0c;希望能够给正在学习java知识的同学带来帮助。 学Java需要下载…

一种新的攻击方式:使用Outlook 表单进行横向渗透和常驻

本文讲的是一种新的攻击方式&#xff1a;使用Outlook 表单进行横向渗透和常驻&#xff0c;背景最近我们针对CrowdStrike服务进行例行调查&#xff0c;发现了一种攻击方法&#xff0c;其主要用于横向渗透和系统常驻&#xff0c;而且是以前我们没有看到过的。这种攻击利用Microso…

ACM 1740 A New Stone Game http://acm.pku.cn/JudgeOnline/problem?id=1740

题目大意:有N堆石头,每堆石头数目在1到100之间,最多有10堆.两人分别取走石头.取石头的规则是:每次只能从1堆中取,每次取走至少1个.取过后还可以把这堆的石头任意分配到其它堆上(这些堆必须有石头,废话呵呵),当然也可以不分配.问给定这些石头堆的情况,两人轮流取,谁先取完谁胜利…

LeetCode实战:回文数

题目英文 Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example 1: Input: 121 Output: trueExample 2: Input: -121 Output: false Explanation: From left to right, it reads -121. From ri…

安全测试的基本原则有哪些?

软件测试顾名思义就是要进行软件安全方面的测试&#xff0c;对于软件测试人员来说&#xff0c;软件安全是一个广泛而复杂的主题&#xff0c;完全避免软件安全缺陷问题是不切实际的&#xff0c;但通过安全测试可以发现并修复软件大部分安全缺陷。下面介绍一些安全测试的基本原则…

LeetCode实战:盛最多水的容器

题目英文 Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a conta…

微软极品Sysinternals Suite工具包使用指南

微软极品Sysinternals Suite工具包使用指南 按照名称首字母排序&#xff0c;点击每个蓝色标题链接都可以转到微软的对应官方页面&#xff0c;有对这些工具包的直接下载地址和更详尽的用法。因为每个软件几乎都可以长篇大论的介绍&#xff0c;所以&#xff0c;在此就只做简介和罗…

【布局】圣杯布局双飞翼布局

背景 随着前端技术的发展推进&#xff0c;web端的布局方式已基本成熟&#xff0c;那么在网站布局方式中&#xff0c;三列布局最为常用&#xff0c;布局方式也有很多&#xff0c;渐渐的开发者们开始从效率的角度优化自己的代码“如果三排布局能将中间的模块放在dom树前面&#x…

UI设计师面试如何操作才能获得高薪

UI设计师在近几年是非常吃香的&#xff0c;求职招聘网站上对于UI设计师的要求也越来越高&#xff0c;那么在面试的过程中UI设计师面试如何操作才能获得高薪呢?来看看下面的详细解析。 UI设计师面试如何操作才能获得高薪? 1、行为举止得体大方 我们先从仪态体态方面说&#xf…

HDU2673-shǎ崽(水题)

如果不能够直接秒杀的题&#xff0c;就不算水题。又应证了那句话&#xff0c;有时候&#xff0c;如果在水题上卡住&#xff0c;那么此题对于你来说&#xff0c;也就不算是水题了额~~ 刚睡醒&#xff0c;迷迷糊糊。 题目的意思很简单&#xff0c;求一个最大的&#xff0c;再求一…

center os7 安装mysql

安装mariadb MariaDB数据库管理系统是MySQL的一个分支&#xff0c;主要由开源社区在维护&#xff0c;采用GPL授权许可。开发这个分支的原因之一是&#xff1a;甲骨文公司收购了MySQL后&#xff0c;有将MySQL闭源的潜在风险&#xff0c;因此社区采用分支的方式来避开这个风险。M…

LeetCode实战:最长公共前缀

题目英文 Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string “”. Example 1: Input: ["flower","flow","flight"] Output: "fl"…

软件测试培训需要学习什么技术

软件测试技术相对于IT行业的其他技术&#xff0c;学习起来是比较简单的&#xff0c;大多数零基础学员想要进入到IT行业都会优先选择软件测试&#xff0c;那么具体软件测试培训需要学习什么技术呢?来看看下面的介绍就知道了。 软件测试培训需要学习什么技术? 每个软件在上线之…

检测晃动的三种方法

http://stackoverflow.com/questions/150446/how-do-i-detect-when-someone-shakes-an-iphone 我的实现&#xff08;基于Eran Talmor&#xff09;&#xff1a; 没必要application.applicationSupportsShakeToEdit YES; Set the applicationSupportsShakeToEdit property in th…

android随手记

Linearlayout:   gravity&#xff1a;本元素中所有子元素的重力方向   layout_gravity&#xff1a;本元素对于父元素的重力方向 自定义权限:http://www.cnblogs.com/it-tomorrow/p/4115161.html 注意:1 .在被调用时就算是normal权限也需要在加入,不然会permission Deney,在…

LeetCode实战:最接近的三数之和

题目英文 Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. Example: Given ar…

零基础学习UI设计有哪些简单有效的方法

UI设计的普及让越来越多的人对UI有了重新的认识&#xff0c;很多企业对UI设计这个岗位都是非常重视的&#xff0c;如今很多零基础学员都想要转行做UI设计&#xff0c;那么针对零基础学习UI设计有哪些简单有效的方法呢?来看看下面的详细介绍吧。 零基础学习UI设计有哪些简单有效…

(转)linux下oracle instant client安装和运行

1.首先要知道什么是ORACLE的客户端&#xff1a; Oracle Instant client 是oracle提供的简便客户端, 支持多种平台. 可从oracle网站下载, 下载地址为http://www.oracle.com/technology/tech/oci/instantclient/index.html 包括如下内容: Instant client Package - Basic 运行OCI…

LeetCode实战:删除排序数组中的重复项

题目英文 Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra me…

16G 手机清理

1.16G 手机清理 清理top 5 的应用的缓存即可 2,hw wife 连接模块 低于 app wifi 的连接模块。 在同样的电脑热点面前&#xff0c;hw 连补上电脑热点&#xff0c;apple 可以连上电脑热点。 其他差异不大。 2.奇兔刷机 tencent应用宝 and 手机管理&#xff0c;备份软件 http://w…

java培训有哪些收费标准

随着学习java技术的人越来越多&#xff0c;市面上的java培训机构也越来越多&#xff0c;每家机构的收费标准都不一样&#xff0c;这让很多想要学习java技术的小伙伴都比较头疼&#xff0c;下面小编就为大家详细的介绍一下java培训有哪些收费标准?如何来评判适合自己的java培训…

使用ASP.NET操作IIS7中使用应用程序

在最新发布的启明星Portal里&#xff0c;增加了安装程序&#xff0c;下面说一下.NET对IIS7操作。IIS7的操作和IIS5/6有很大的不同&#xff0c;在IIS7里增加了 Microsoft.Web.Administration 命名空间里&#xff0c;增加了ServerManager、Site几个大类来操作IIS7。 下面是一些核…

MYSQL体系结构-来自期刊

MYSQL体系结构-来自期刊 MySQL三层体系结构|-----------------------------------------------------------------------------------| | mysqld-SQL层 | |-------------------------------------------…

LeetCode实战:搜索旋转排序数组

题目英文 Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You are given a target value to search. If found in the array return its index, otherwise retur…

Python内置数据结构之双向队列

经常听说Python就是一门执行速度低的语言&#xff0c;可能是你的程序中使用了复杂的算法与数据结构&#xff0c;才会导致程序执行速率低的。在Python的标准库中提供了常见的数据结构工开发者使用&#xff0c;不仅执行速率比较快&#xff0c;还可以简化开发者的编程工作。下面我…

C# GDAL 学习一

最近一直琢磨如何用C#GDAL读取栅格数据&#xff08;.tif或.img&#xff09;&#xff0c;运气不错的在GDAL 的官网上找到一部分源码。经过本人测试&#xff0c;效果还不错。学习还将继续深入下去。 参考网址&#xff1a;http://trac.osgeo.org/gdal/browser/trunk/gdal/swig/csh…

LeetCode实战:字符串相加

题目英文 Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. Note: The length of both num1 and num2 is < 5100.Both num1 and num2 contains only digits 0-9.Both num1 and num2 does not contain any leadin…

js中修改this的指向方法整理

JavaScript(简称“JS”) 是一种具有函数优先的轻量级&#xff0c;解释型或即时编译型的编程语言。虽然它是作为开发Web页面的脚本语言而出名&#xff0c;但是它也被用到了很多非浏览器环境中&#xff0c;JavaScript 基于原型编程、多范式的动态脚本语言&#xff0c;并且支持面向…