Convert String to Long

时间:2023-03-09 19:41:22
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.

代码:

 /*
* Author: Min Li
* Discussion:
* 1. Return 0 when input is not valid (Empty or wrong format)
* 2. Return LONG_MAX when input string overflows
* 3. Return LONG_MIN when input string underflows
* 4. Input String is allowed to have additional character after a valid substring that can form a long number. (e.g. +123+)
* 5. Input can have many whitespaces before the first non-whitespace character. (e.g. " 123")
*
*/ // Class: Solution class Solution {
public:
// Method: Convert String to Long
long stringToLong(string s) {
// Special Case: Empty
if(s.size()==)
return ;
long sign; // Record the sign of the long number
int index=;
int strLen = s.size(); // The length of input
long result=; // The final result
// Discard the whitespaces before the first non-whitespace.
while(index<strLen && s[index]==' ') index++; // The input only contains whitespaces
if(index==strLen)
return ; // Determine the sign
if(s[index]=='-') { // Input starts with "-"
sign = -;
++index;
}
else if(s[index]=='+') { // Input starts with "+"
sign = ;
++index;
}
else if(s[index] < '' || s[index] > '') // Invalid input
return ;
else // Unsigned input
sign = ; // Retrieve the digit after first non-whitespace character
while(index<strLen) {
if(s[index]>='' && s[index]<='') { // New character is 0-9
int digit = s[index]-'';
if(result>LONG_MAX/ || (result==LONG_MAX/ && digit>LONG_MAX%)) { // Overflow or underflow
result = sign==-?LONG_MIN:LONG_MAX;
}
else
result = result*+digit;
}
else // New character is not 0-9
break;
index++;
} return sign*result; } // Method: Test
void test() {
string testString;
// testString = ""; // Test Case 1: Empty
testString = ""; // Test Case 2: Valid unsigned input
// testString = "+123"; // Test Case 3: Valid signed input
// testString = " 123"; // Test Case : Valid input with whitespaces
// testString = "abc123"; // Test Case : Invalid input
// testString = "++123"; // Test Case 4: Invalid signed input
// testString = "+123+"; // Test Case 5: Valid input format with additional characters
// testString = "3924x8"; // Test Case 6: Invalid input format
// testString = "1000000000000000000000"; // Test Case 7: Overflow
// testString = "-10000000000000000000"; // Test Case 8: Underflow
cout << stringToLong(testString) << endl;
}
};