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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

字符串转化为整数

發布時間:2024/4/17 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 字符串转化为整数 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目:

字符串轉換為整數 : atoi

可能的輸入:
1 帶符號數
2 無符號數
3 零
4 空指針
5 超出表示范圍 – 暫時僅僅是直接退出且設置最小 – 可以考慮此時拋個異常
6 非法輸入,比如并不是一個0-9或者+ -組成的字符串 – 對于非法輸入一律返回的是Integer.MIN_VALUE

?

解答:

1 public class Solution { 2 3 public static long strToInt(String str) { 4 if(str == null) { 5 return Long.MIN_VALUE; 6 } 7 8 if(str.length() == 0) { 9 return 0; 10 } 11 12 for(int i = 0; i < str.length(); i++) { 13 if(!judge(str.charAt(i))) { 14 return Long.MIN_VALUE; 15 } 16 } 17 18 char[] chars = str.toCharArray(); 19 long result = 0; 20 21 if(char[0] == '+' || char[0] == '-') { 22 result = trans(str.substring(1)); 23 } else { 24 result = trans(str); 25 } 26 27 if(result > 0 && char[0] == '-') { 28 result = -result; 29 } 30 31 return result; 32 } 33 34 public static boolean judge(char c) { 35 if(c == '+' || c == '-' || (c >= '0' && c <= '9')) { 36 return true; 37 } else { 38 return false; 39 } 40 } 41 42 private static long trans(String str) { 43 if(str.length() == 0) { 44 return 0; 45 } 46 47 long result = 0; 48 for(int i = 0; i < str.length(); i++) { 49 result = result*10 + str.charAt(i)-'0'; 50 51 // important here 52 if(result > Long.MAX_VALUE) { 53 result = Long.MAX_VALUE; 54 break; 55 } 56 } 57 58 return result; 59 } 60 }

?

轉載于:https://www.cnblogs.com/wylwyl/p/10477256.html

總結

以上是生活随笔為你收集整理的字符串转化为整数的全部內容,希望文章能夠幫你解決所遇到的問題。

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