Convert String to Long

问题:

Given a string, write a routine that converts the string to a long, without using the built in functions that would do this. Describe what (if any) limitations the code has.

代码:

 1 /*
 2  * Author: Min Li
 3  * Discussion:
 4  *    1. Return 0 when input is not valid (Empty or wrong format)
 5  *    2. Return LONG_MAX when input string overflows
 6  *    3. Return LONG_MIN when input string underflows
 7  *    4. Input String is allowed to have additional character after a valid substring that can form a long number. (e.g. +123+)
 8  *    5. Input can have many whitespaces before the first non-whitespace character. (e.g. "    123")
 9  *
10  */
11
12
13 // Class: Solution
14
15 class Solution {
16 public:
17     // Method: Convert String to Long
18     long stringToLong(string s) {
19         // Special Case: Empty
20         if(s.size()==0)
21           return 0;
22         long sign;                                          // Record the sign of the long number
23         int index=0;
24         int strLen = s.size();                              // The length of input
25         long result=0;                                      // The final result
26         // Discard the whitespaces before the first non-whitespace.
27         while(index<strLen && s[index]==‘ ‘) index++;
28
29         // The input only contains whitespaces
30         if(index==strLen)
31           return 0;
32
33         // Determine the sign
34         if(s[index]==‘-‘) {                                 // Input starts with "-"
35           sign = -1;
36           ++index;
37         }
38         else if(s[index]==‘+‘) {                            // Input starts with "+"
39           sign = 1;
40           ++index;
41         }
42         else if(s[index] < ‘0‘ || s[index] > ‘9‘)           // Invalid input
43           return 0;
44         else                                                // Unsigned input
45           sign = 1;
46
47         // Retrieve the digit after first non-whitespace character
48         while(index<strLen) {
49             if(s[index]>=‘0‘ && s[index]<=‘9‘) {                                          // New character is 0-9
50                 int digit = s[index]-‘0‘;
51                 if(result>LONG_MAX/10 || (result==LONG_MAX/10 && digit>LONG_MAX%10)) {      // Overflow or underflow
52                     result = sign==-1?LONG_MIN:LONG_MAX;
53                 }
54                 else
55                    result = result*10+digit;
56             }
57             else                                                                          // New character is not 0-9
58                 break;
59             index++;
60         }
61
62
63         return sign*result;
64
65     }
66
67     // Method: Test
68     void test() {
69         string testString;
70 //        testString = "";                        // Test Case 1: Empty
71         testString = "123";                        // Test Case 2: Valid unsigned input
72 //        testString = "+123";                    // Test Case 3: Valid signed input
73 //        testString = "   123";                  // Test Case  : Valid input with whitespaces
74 //        testString = "abc123";                  // Test Case  : Invalid input
75 //        testString = "++123";                    // Test Case 4: Invalid signed input
76 //        testString = "+123+";                    // Test Case 5: Valid input format with additional characters
77 //        testString = "3924x8";                    // Test Case 6: Invalid input format
78 //        testString = "1000000000000000000000";         // Test Case 7: Overflow
79 //        testString = "-10000000000000000000";          // Test Case 8: Underflow
80      cout << stringToLong(testString) << endl;
81     }
82 };
时间: 2024-10-25 22:31:27

Convert String to Long的相关文章

svn: Can&amp;#39;t convert string from &amp;#39;UTF-8&amp;#39; to native encoding 解决的方法

今天在down代码时遇到了例如以下问题: [[email protected] ~]$ svn co https://xxxxxxxxxxxxx svn: Can't convert string from 'UTF-8' to native encoding: svn: xxxxxxxx/include/xml_inc/XML/?\194?\184? \194? \180?\194?\188?\195? \190 mcXML.h 这个问题主要是代码中包括了中文名字的文件,svn这边的编码不支持

svn: Can&#39;t convert string from &#39;UTF-8&#39; to native encoding: 解决办法

在linux中,svn co 或 svn up 时有中文文件名的文件的话,可能会报下面的错: [[email protected]-dev-srv1 ~]# svn upsvn: Can't convert string from 'UTF-8' to native encoding:svn: src/main/webapp/resources/js/My97DatePicker/?\229?\188?\128?\229?\143?\145?\229?\140?\133 先locale看一下系统

svn: Can&#39;t convert string from native encoding to &#39;UTF-8&#39;:

在bash的shell下,输入如下命令: #export LC_CTYPE=en_US.UTF-8 #!/bin/sh export LC_CTYPE=en_US.UTF-8 svn up /home/wwwroot/zj/erp --username "tcy" --password "zj004" http://blog.csdn.net/dazhi_100/article/details/17148987 svn: Can't convert string f

The method convert(String) of type DateConverter must override a superclass method

那是因为你的Compiler 是jdk1.5,只要把它改为 1.6就可以了 方法: j2ee换成 7 The method convert(String) of type DateConverter must override a superclass method

SVN遇到Can&#39;t convert string from &#39;UTF-8&#39; to native encoding

svn co代码的时候遇到问题 svn: Can't convert string from 'UTF-8' to native encoding: svn: platform/console-framework/portal/img/zhanzhang_logo - ?\226?\148?\130?\206?\149.png 用  locale 命令检查下机器的语言环境 如果直接执行 export LANG="zh_CN.UTF-8" 那么修改的将是当前终端的语言环境,关闭后再连接还

反序列化Newtonsoft.Json.JsonReaderException:“Could not convert string to decimal: . Path &#39;SETTLEAMT&#39;, line 1, position 180.”

一个小小的问题 我居然纠结了小半天,我也是醉醉的了喔,天啊 到最后发现.....的问题,之前总感觉是我写法或者哪里的小细节的地方呢,我去  着急的我都想讲 脏话了,嗯 稳住  淑女 调试到这里的时候一直感觉 没有问题啊,哪里的问题...   然后  换了一下思路,代码 确实 没啥问题   要不把这个引用的Newtonsoft.json  更新一个版本试试   报着千个 不服的态度更新了,这个结果让我眼前一亮... 更新  更新 运行 测试程序     啊啊啊啊  不是我的问题  是版本 是版本

C# Newtonsoft.Json.JsonReaderException:“Could not convert string to decimal:

使用Newtonsoft.Json,报以上错误,问题的原因是有"",把“”替换成null: 以前的json: [{"WengvNj":"df5c38c6dd1744c59605da1fc85a0500","WengvSgtm":"2019-12-16 修理合同","WengvSu":"2019TJR001LX","WengvYewm":"

Write a program to convert string to number without using library function。

1.问题 /* */ 2.算法 #define MAX_LONG 0X7FFFFFFF long foo(const char* str) { int sign = 1 ; long num = 0 ; const char* p = str ; //假设输入的字符串是合法的 if ( *p == '-' ) { sign = -1 ; p++ ; }else if ( *p == '+' ) { sign = 1 ; p++ ; } while(*p) { if ( (num > LONG_M

easy.py使用中ValueError: could not convert string to float: svm_options错误问题解决

在使用easy.py中出现如下图所示问题 解决方法: 1.找到cmd = '{0} -svmtrain "{1}" -gnuplot "{2}" "{3}"'.format(grid_py, svmtrain_exe, gnuplot_exe, scaled_file) 2.将其改为cmd = 'python {0} -svmtrain "{1}" -gnuplot "{2}" "{3}"