leetcode文字列は文字列を数値に変換します

記事のディレクトリ

THE

問題

ここに画像の説明を挿入

解決

コード



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

-  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