leetcode string 字符串转成数字

O

问题

在这里插入图片描述

解决方案

代码



/*
思路: 这道题使用遍历加多层条件控制去解决。 属于细节题。 

-  define  int nums 
- if first == '+' num = 1; else =='-' num = -1
-  for(....)  //  data from end to front
- -  if (data in 0-9) num = num*10+data;
- -  else return 0;
- return nums;
*/

class Solution {
    
    
public:
   int StrToInt(string str) {
    
    
       int num = 0;
       if(str[0]>'0'&&str[0]<'9'){
    
    
           for(int i =0 ; i<str.size();i++){
    
    
               if(str[i]>'0'&&str[i]<'9'){
    
    
                   int temp = str[i]- '0';
                   num = num*10+temp ;
               }
               else return 0;
           }            
       }
       else if(str[0] =='+'||str[0] =='-'){
    
    
           for(int i =1 ; i<str.size();i++){
    
    
               if(str[i]>'0'&&str[i]<'9'){
    
    
                   int temp = str[i]- '0';
                   num = num*10+temp ;
               }
               else return 0;
           }
           if(str[0] =='+')num *=  1;
           else if(str[0]=='-') num *= -1;            
       }
       else return 0;        
       return num;
       
   }
};

总结与反思

  1. 注意 不同情况应该如何去解决。 题目不难, 细节比较多。

猜你喜欢

转载自blog.csdn.net/liupeng19970119/article/details/114186919