zoukankan      html  css  js  c++  java
  • atof

    So given a string like "2.23" your function should return double 2.23. This might seem easy in the first place but this is a highly ambiguous question. Also it has some interesting test cases. So overall a good discussion can revolve around this question. We are not going to support here scientific notation like 1.45e10 etc. We will also not support hex and octal strings just for the sake of simplicity. But these are good assumption to state upfront. Let's write code for this.
    
    double atof(char* num)
     {
         if (!num || !*num)
             return 0; 
         double integerPart = 0;
         double fractionPart = 0;
         int divisorForFraction = 1;
         int sign = 1;
         bool inFraction = false;
         /*Take care of +/- sign*/
         if (*num == '-')
         {
             ++num;
             sign = -1;
         }
         else if (*num == '+')
         {
             ++num;
         }
         while (*num != '')
         {
             if (*num >= '0' && *num <= '9')
             {
                 if (inFraction)
                 {
                     /*See how are we converting a character to integer*/
                     fractionPart = fractionPart*10 + (*num - '0');
                     divisorForFraction *= 10;
                 }
                 else
                 {
                     integerPart = integerPart*10 + (*num - '0');
                 }
             }
             else if (*num == '.')
             {
                 if (inFraction)
                     return sign * (integerPart + fractionPart/divisorForFraction);
                 else
                     inFraction = true;
             }
             else
             {
                 return sign * (integerPart + fractionPart/divisorForFraction);
             }
             ++num;
         }
         return sign * (integerPart + fractionPart/divisorForFraction);
     }
  • 相关阅读:
    20181030-4 每周例行报告
    20181023-3 每周例行报告
    20181016-10 每周例行报告
    PSP总结报告
    第十二周例行报告
    对团队成员公开感谢
    第十一周例行报告
    第十周例行报告
    第九周例行报告
    第八周例行报告
  • 原文地址:https://www.cnblogs.com/graph/p/3364339.html
Copyright © 2011-2022 走看看