将字符串转换为数字

淡淡的烟草味﹌ 2022-05-24 03:22 433阅读 0赞

这里写图片描述

  1. public class Solution {
  2. public int StrToInt(String str) {
  3. if(str==null||str.length()==0)
  4. return 0;
  5. int count=0;
  6. boolean tag=true;
  7. if(str.charAt(0)!='-'&&str.charAt(0)!='+'&&
  8. (str.charAt(0)<48||str.charAt(0)>57||str.charAt(0)=='0'))
  9. {
  10. return 0;
  11. }
  12. if(str.charAt(0)=='-') //第一个符号为负号
  13. {
  14. tag=false;
  15. }
  16. if(str.charAt(0)!='+'&&tag) //第一个符号为数字
  17. count=(str.charAt(0)-48)*(int)Math.pow(10,str.length()-1);
  18. for(int i=1;i!=str.length();i++)
  19. {
  20. if(str.charAt(i)>=48&&str.charAt(i)<=57)
  21. {
  22. count+=(str.charAt(i)-48)*(int)Math.pow(10,str.length()-i-1);
  23. }else{
  24. return 0;
  25. }
  26. }
  27. if(!tag)
  28. {
  29. count*=-1;
  30. }
  31. return count;
  32. }
  33. public static void main(String[]args){
  34. //System.out.println("Hello");
  35. Solution s=new Solution();
  36. System.out.println(s.StrToInt("+2147483647"));
  37. }
  38. }

这里写图片描述

发表评论

表情:
评论列表 (有 0 条评论,433人围观)

还没有评论,来说两句吧...

相关阅读

    相关 字符串转换数字

    声明:题目来源于《王道》 问题描述:输入一个表示整数的字符串,把该字符串转换成整数并输出。例如,输入字符串“12345”,输出整数“12345”。 解决方法:依次扫描字符串