Convert string to float

  • 1

    Given a string that only contains digit 0-9, dot(.), 'e' and negative sign '-', your task is converting the given string to a float number.

    for example:
    "0.0006" => 0.0006
    "6e-4" => 0.0006

  • 0

    ensure that input in valid? behind e, it must be a number ? is -e valid? or e-8 or 1e-8?

  • -1
    double convert(string s){
      double ans = 0;
      int i=0, n=s.size();
      while(i<n && s[i]!='.' && s[i]!='e') ans= ans*10+s[i]-'0', i++;
      if(i>=n) return ans;
        double w = 0.1;
        while(i<n && s[i]!='e') ans+=w*(s[i]-'0'), w/=10, i++;;
      if(i>=n) return ans;
      int exp=0;
      bool flag=0;//0 means +, 1 means -
      if(i<n && s[i]=='+') i++;
      else if(i< n && s[i]=='-') i++, flag=1;
      while(i<n) exp=exp*10+s[i]-'0', i++;
      if(!flag) ans = ans * pow(10, exp);
      else ans = ans/ pow(10, exp);
      return ans;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.