current position:Home>Power button (LeetCode) 65. Significant figures (c + +)

Power button (LeetCode) 65. Significant figures (c + +)

2022-11-24 22:18:43clear ink rhyme dyeing

模拟

Test case-oriented programming,Imagine the picture of engineering development.改需求,Code can also be streamlined!

First determine the sign of the first digit,Remove the plus and minus signs,If there is only one sign character,false.
判断 ′ . ′ '.' . ,如果是单独的 ′ . ′ '.' . ,false ,如果 ′ . ′ '.' . 后面有 ′ e ′ 'e' e ′ E ′ 'E' E ,false.
维护两个变量,记录 ′ . ′ '.' . ′ e ′ 'e' e 出现的次数,进入循环.
遇到 ′ . ′ '.' . ,如果 ′ . ′ '.' . 出现过,false.
遇到 ′ e ′ 'e' e,如果 ′ e ′ 'e' e 出现过,或者 ′ e ′ 'e' e first or last,false. ′ e ′ 'e' e A plus or minus sign can be followed,If the sign is in the last place,false.
遇到非数字,false.
escape the loop,true.

class Solution {
    
public:
    bool isNumber(string s) {
    //模拟
        if('+'==s[0]||'-'==s[0]) s = s.substr(1);
        if(s.empty()) return false;
        int dot = 0, e= 0;
        if('.'==s[0]&&(1==s.size()||s[1]=='e')) return false;
        for(int i = 0;i<s.size();i++){
    
            if('.'==s[i]){
    
                if(e>0||dot>0) return false;
                dot++;
            }else if('e'==s[i]||'E'==s[i]){
    
                if(e>0||0==i||i==s.size()-1) return false;
                e++;
                if('-'==s[i+1]||'+'==s[i+1]){
    
                    i++;
                    if(s.size()-1==i) return false;
                }
            }else if (s[i]>'9'||s[i]<'0') return false;
        }
        return true;
    }
};

时间复杂度 O ( n ) O(n) O(n) , The time complexity of traversing the string once O ( n ) O(n ) O(n) .

空间复杂度 O ( 1 ) O(1) O(1) ,Only constant-level space is used.

致语

Understanding the train of thought is not important,I am also programming for test cases.
欢迎读者在评论区留言,答主看到就会回复的.

AC

AC

copyright notice
author[clear ink rhyme dyeing],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/328/202211242213164446.html

Random recommended