日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Leet Code OJ 8. String to Integer (atoi) [Difficulty: Easy]

發布時間:2024/2/28 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Leet Code OJ 8. String to Integer (atoi) [Difficulty: Easy] 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目:
Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

翻譯:
實現一個atoi函數來把字符串轉換為整型變量。

分析:
這道題的AC率只有13.4%,主要是因為對特殊情況的處理上。具體有這么幾種情況需要考慮:
1. 前面的空格
2. 除去前面的空格后,可以以“+、-、0”開頭,需要做對應的處理
3. 除了起始處可以出現前2種情況提到的非數字字符,其他地方一旦出現,則忽略該字符以及其后的字符
4. 考慮邊界,即是否超出Integer.MAX_VALUE,Integer.MIN_VALUE。下面的方案采用long作為臨時存儲,方便做邊界的判斷。但是還要考慮是否會超出long的最大值,所以筆者采用length長度做初步判斷。

Java版代碼(時間復雜度O(n)):

public class Solution {public int myAtoi(String str) {char[] charArr=str.toCharArray();Long result=0L;int startIndex=0;boolean flag=true;//正數int length=0;for(int i=0;i<charArr.length;i++){if(startIndex==i){if(charArr[i]==' '){startIndex++;continue;}if(charArr[i]=='+'||charArr[i]=='0'){continue;}if(charArr[i]=='-'){flag=false;continue;}}if(charArr[i]>='0'&&charArr[i]<='9'){result=result*10+charArr[i]-'0';length++;if(length>10){break;}}else{break;}}if(flag){if(result>Integer.MAX_VALUE){return Integer.MAX_VALUE;}}else{result=-result;if(result<Integer.MIN_VALUE){return Integer.MIN_VALUE;}}return result.intValue();} }

總結

以上是生活随笔為你收集整理的Leet Code OJ 8. String to Integer (atoi) [Difficulty: Easy]的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。