Saturday, July 19, 2008

string integer conversions (atoi, itoa)

In atoi, we have to check for special conditions like the first character for a sign, if Si is not within 0 and 9 then we return the num we have so far, if there is an overflow by num = num * 10 + Si.

int atoi (string s):
    int num = 0
    int i = 0
    bool neg = false
    if s[0] == '-':
        neg = true
        i = 1
    if s[0] == '+':
        i = 1
    for (; i< len(s); i++): 
        if (s[i] - '0' < 0 || s[i] - '0' > 9):
            break
        num = num * 10 + s[i] - '0' // possible overflow
    if neg:
        num = -1 * num
    return num

You need only 10 inputs to test this function. Inputs in italics are not necessary.

//smoke / basic
123, -123
123F1, -123f1
//hard
INT_MAX, INT_MIN
+123
//boundary values
0, null, "" (empty), " " (blank), a
// not required
abc (covered by a)
INT_MAX +1, INT_MIN -1 (requirement does not state this)

[Hat tip to PIE, JE]

itoa seems to lack special conditions comparatively.

string itoa (int num):
    stringBuffer sb = new stringBuffer();
    bool neg = false
    if num < 0: 
        neg = true
        num = num * -1 
    while (num > 0):
        sb.insert(0, (char) num %10 + '0')
        num = num /10
    if neg:
        sb.insert(0, '-')
    return sb.toString()


[Hat tip to PIE]

No comments:

Post a Comment