[剑指offer]面试题第[67]题[Leetcode][JAVA][第8题] 字符串转换整数 (atoi)[字符串]

【问题描述】

请你来实现一个 atoi 函数,使其能将字符串转换成整数。首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。接下来的转化规则如下:如果第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字字符组合起来,形成一个有符号整数。
假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成一个整数。
该字符串在有效的整数部分之后也可能会存在多余的字符,那么这些字符可以被忽略,它们对函数不应该造成影响。
注意:假如该字符串中的第一个非空格字符不是一个有效整数字符、字符串为空或字符串仅包含空白字符时,则你的函数不需要进行转换,即无法进行有效转换。在任何情况下,若函数不能进行有效的转换时,请返回 0 。提示:本题中的空白字符只包括空格字符 ' ' 。
假设我们的环境只能存储 32 位大小的有符号整数,那么其数值范围为 [−231,  231 − 1]。如果数值超过这个范围,请返回  INT_MAX (231 − 1) 或 INT_MIN (−231) 。示例:输入: "-91283472332"
输出: -2147483648
解释: 数字 "-91283472332" 超过 32 位有符号整数范围。 因此返回 INT_MIN (−231) 。

【解答思路】

1. 考虑所有情况 空格 符号 是否数字 上界

时间复杂度:O(N) 空间复杂度:O(1)

特别注意:

1、由于题目中说「环境只能保存 32 位整数」,因此这里在每一轮循环之前先要检查乘以 1010 以后是否溢出,具体细节请见编码。
2、Java 、Python 和 C++ 字符串的设计都是不可变的,即使用 trim() 会产生新的变量,因此我们尽量不使用库函数,使用一个变量 index 去做遍历,这样遍历完成以后就得到转换以后的数值。

威威的工程代码

public class Solution {public int myAtoi(String str) {int len = str.length();// str.charAt(i) 方法回去检查下标的合法性,一般先转换成字符数组char[] charArray = str.toCharArray();// 1、去除前导空格int index = 0;while (index < len && charArray[index] == ' ') {index++;}// 2、如果已经遍历完成(针对极端用例 "      ")if (index == len) {return 0;}// 3、如果出现符号字符,仅第 1 个有效,并记录正负int sign = 1;char firstChar = charArray[index];if (firstChar == '+') {index++;} else if (firstChar == '-') {index++;sign = -1;}// 4、将后续出现的数字字符进行转换// 不能使用 long 类型,这是题目说的int res = 0;while (index < len) {char currChar = charArray[index];// 4.1 先判断不合法的情况if (currChar > '9' || currChar < '0') {break;}// 题目中说:环境只能存储 32 位大小的有符号整数,因此,需要提前判:断乘以 10 以后是否越界if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && (currChar - '0') > Integer.MAX_VALUE % 10)) {return Integer.MAX_VALUE;}if (res < Integer.MIN_VALUE / 10 || (res == Integer.MIN_VALUE / 10 && (currChar - '0') > -(Integer.MIN_VALUE % 10))) {return Integer.MIN_VALUE;}// 4.2 合法的情况下,才考虑转换,每一步都把符号位乘进去res = res * 10 + sign * (currChar - '0');index++;}return res;}public static void main(String[] args) {Solution solution = new Solution();String str = "2147483646";int res = solution.myAtoi(str);System.out.println(res);System.out.println(Integer.MAX_VALUE);System.out.println(Integer.MIN_VALUE);}
}作者:liweiwei1419
链接:https://leetcode-cn.com/problems/string-to-integer-atoi/solution/jin-liang-bu-shi-yong-ku-han-shu-nai-xin-diao-shi-/
2. 时间复杂度:O(N) 空间复杂度:O(1)

甜姨的刀法

public class Solution {public int myAtoi(String str) {char[] chars = str.toCharArray();int n = chars.length;int idx = 0;while (idx < n && chars[idx] == ' ') {// 去掉前导空格idx++;}if (idx == n) {//去掉前导空格以后到了末尾了return 0;}boolean negative = false;if (chars[idx] == '-') {//遇到负号negative = true;idx++;} else if (chars[idx] == '+') {// 遇到正号idx++;} else if (!Character.isDigit(chars[idx])) {// 其他符号return 0;}int ans = 0;while (idx < n && Character.isDigit(chars[idx])) {int digit = chars[idx] - '0';if (ans > (Integer.MAX_VALUE - digit) / 10) {// 本来应该是 ans * 10 + digit > Integer.MAX_VALUE// 但是 *10 和 + digit 都有可能越界,所有都移动到右边去就可以了。return negative? Integer.MIN_VALUE : Integer.MAX_VALUE;}ans = ans * 10 + digit;idx++;}return negative? -ans : ans;}
}作者:sweetiee
链接:https://leetcode-cn.com/problems/string-to-integer-atoi/solution/java-zi-fu-chuan-zhuan-zheng-shu-hao-dong-by-sweet/
3.思路

在这里插入图片描述

class Solution {public int strToInt(String str) {char[] c = str.trim().toCharArray();if(c.length == 0) return 0;int res = 0, bndry = Integer.MAX_VALUE / 10;int i = 1, sign = 1;if(c[0] == '-') sign = -1;else if(c[0] != '+') i = 0;for(int j = i; j < c.length; j++) {if(c[j] < '0' || c[j] > '9') break;//c[j] > '7' 这里处理很巧妙,判断 > '7' , 看似没有考虑 MIN, 但其实无论是 = '8' ,还是 >'8',返回的都是MIN。 学习了if(res > bndry || res == bndry && c[j] > '7') return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;res = res * 10 + (c[j] - '0');}return sign * res;}
}作者:jyd
链接:https://leetcode-cn.com/problems/ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof/solution/mian-shi-ti-67-ba-zi-fu-chuan-zhuan-huan-cheng-z-4/
来源:力扣(LeetCode)

【总结】

1.威威&&甜姨工作心得

-有现成的工具和类库需尽量使用,因为它们是性能更优,且经过更严格测试,是相对可靠的;
-能抽取成工具类、工具方法的尽量抽取,以突出主干逻辑、方便以后代码复用;
-不得不写得比较繁琐、冗长的时候,需要写清楚注释、体现逻辑层次,以便上线以后排查问题和后续维护
-等真正工作以后,尽可能地调用jdk的方法,比如Character.isDigit。如果没有你想要的api,也要尽量使用guava,apache common等常见的utils包,尽量不要自己造轮子

2. 提前量思想(生活也得如此)

判断越界 可以考虑打提前量

if (ans > (Integer.MAX_VALUE - digit) / 10) {// 本来应该是 ans * 10 + digit > Integer.MAX_VALUE// 但是 *10 和 + digit 都有可能越界,所有都移动到右边去就可以了。return negative? Integer.MIN_VALUE : Integer.MAX_VALUE;}

瑞幸财务造假

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/426053.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

java 面板 选择颜色_[代码全屏查看]-java颜色选择器

[1].[代码] [Java]代码package com.liuxing.test;import java.awt.Color;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JColorChooser;import javax.swing.JFrame;import javax.swing.JLabel;impor…

java学习(141):自定义捕捉异常

//自定义异常类 public class ArrayElement extends Exception{public static final int MAX_NUM1000;private static final String MESSAGE"集合存储元素过多";public ArrayElement(){}public String getMessage(){return MESSAGE"最大元素限制为"MAX_NU…

[Leedcode][JAVA][第42题][动态规划][双指针][栈]

【问题描述】 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图&#xff0c;计算按此排列的柱子&#xff0c;下雨之后能接多少雨水。![image.png](https://upload-images.jianshu.io/upload_images/17025746-87f6db1a993ce416.png?imageMogr2/auto-orient/strip%7CimageVie…

java环境变量设置优化_Mac/windows配置jdk环境变量-seo优化只选拉一八科技

Mac/windows配置jdk环境变量Mac配置jdk环境变量直接双击dmg文件&#xff0c;然后单击[下一步]完成安装。请忽略[配置jdk环境变量]直接跳转到[检查jdk是否安装成功]。Windows配置jdk环境变量窗户系统配置1.右键单击桌面上的“计算机”&#xff0c;然后单击“属性”2.单击“高级系…

java学习(142):file类的基本创建

//file类的基本创建 import java.io.File;public class test85 {public static void main(String[] args){//创建文件对象String filePath"e:\\1.txt";File filenew File( filePath );System.out.println( filenull );//无论给定的文件虚拟路径是否存在//创建file在j…

speech模块实现语音识别

1.pip安装speech、pywin32 pip install speech pip install pywin322.例子 #!/usr/bin/python # coding:utf-8 from __future__ import unicode_literals import speech import os import sys import webbrowser__author__ "klx" # Create your views here. phrase …

java phantomjs alert_Python+Selenium+PhantomJS脚本中的Javascript警报

我尝试用Python脚本在DSL调制解调器中“单击”Javascript警报以确认重新启动&#xff0c;如下所示&#xff1a;#!/usr/bin/env pythonimport seleniumimport timefrom selenium import webdrivercap {uacceptSslCerts: True,uapplicationCacheEnabled: True,ubrowserConnectio…

[Leedcode][JAVA][第460题][LFU]

【问题描述】 设计并实现最不经常使用&#xff08;LFU&#xff09;缓存的数据结构。它应该支持以下操作&#xff1a;get 和 put。get(key) - 如果键存在于缓存中&#xff0c;则获取键的值&#xff08;总是正数&#xff09;&#xff0c;否则返回 -1。 put(key, value) - 如果键…

java学习(143):file方法类实现

import java.io.File; import java.io.IOException; import java.net.URI; import java.util.List;//文件管理类 public class FileManager {public static File createFileAction(URI uri){//使用URI做出参数创建对象if(uri!null)return new File( uri );return null;}//dir文…

性能测试十九:jmeter参数优化+排错

一&#xff1a;参数优化 1&#xff0c;控制台取样间隔的设置&#xff0c;在jmeter/bin/jmeter.properties文件中修改 summariser.interval10&#xff0c;默认为30s&#xff0c;最低可修改为6s 2&#xff0c;Jvm参数优化 bin目录下&#xff0c;vi jmeter&#xff0c;修改HEAP的…

pythonxml模块高级用法_Python利用ElementTree模块处理XML的方法详解

前言最近因为工作的需要&#xff0c;在使用 Python 来发送 SOAP 请求以测试 Web Service 的性能&#xff0c;由于 SOAP 是基于 XML 的&#xff0c;故免不了需要使用 python 来处理 XML 数据。在对比了几种方案后&#xff0c;最后选定使用 xml.etree.ElementTree模块来实现。这篇…

java学习(144):file常用方法1

import java.io.File; import java.io.IOException; import java.net.URI; import java.util.List;//文件管理类 public class FileManager {public static File createFileAction(URI uri){//使用URI做出参数创建对象if(uri!null)return new File( uri );return null;}//dir文…

[Leedcode][JAVA][第72题][动态规划]

【问题描述】 [72. 编辑距离] 给你两个单词 word1 和 word2&#xff0c;请你计算出将 word1 转换成 word2 所使用的最少操作数 。你可以对一个单词进行如下三种操作&#xff1a;插入一个字符 删除一个字符 替换一个字符示例 1&#xff1a;输入&#xff1a;word1 "horse&…

Docker操作笔记(二)容器

容器 一、启动容器 启动一个容器有两种方式&#xff1a; 1.基于镜像新键并启动一个容器&#xff1a; 所需要的主要命令为docker run docker run ubuntu:18.04 /bin/echo "hello" #启动一个bash终端 docker run -t -i ubuntu:18.04 /bin/bash 其中&#xff0c;-t 选项…

java学习(145):file常用方法2

import java.io.File; import java.io.IOException; import java.net.URI; import java.util.List;//文件管理类 public class FileManager {public static File createFileAction(URI uri){//使用URI做出参数创建对象if(uri!null)return new File( uri );return null;}//dir文…

java uipath_10.3 UiPath如何调用Java

调用Java方法(Invoke Java Method)的介绍从Java Scope中的.jar加载的方法中调用指定的Java方法。并结果存储在变量中二、Invoke Java Method 在UiPath中的使用打开设计器, 在设计库中新建一个Sequence&#xff0c;为序列命名及设置Sequence存放的路径, 在Activities中搜索Java …

Mybatis注解开发之@Results

写在前面&#xff1a;在使用mybatis注解开发的时候&#xff0c;数据库返回的结果集和实体类字段不对应&#xff0c;我们就需要手动指定映射关系&#xff1b; 一种是使用在xml文件中指定resultMap&#xff0c;指定id&#xff0c;下面需要的直接引用id就可以&#xff1b; 另一种在…

java学习(146):file常用方法3

import java.io.File; import java.io.IOException; import java.net.URI; import java.util.List;//文件管理类 public class FileManager {public static File createFileAction(URI uri){//使用URI做出参数创建对象if(uri!null)return new File( uri );return null;}//dir文…

[算法][二分查找][排除法]

最基本的二分查找算法 「搜索区间」是 [left, right] nums[mid] target 时可以立即返回 int binary_search(int[] nums, int target) {int left 0, right nums.length - 1; while(left < right) {int mid left (right - left) / 2;//防止大数溢出if (nums[mid] < t…

php getcount_PHP中关键字interface和implements详解

搜索热词PHP 类是单继承&#xff0c;也就是不支持多继承&#xff0c;当一个类需要多个类的功能时&#xff0c;继承就无能为力了&#xff0c;为此 PHP 引入了类的接口技术。如果一个抽象类里面的所有方法都是抽象方法&#xff0c;且没有声明变量&#xff0c;而且接口里面所有的成…