Implement an Integer to String Subrouting

The function should take an integer as input and should return the string without using any of the "print" functions


In [18]:
def itoa_example(i):
    return "The number is %d"%i

print(itoa_example(5745))


The number is 5745

In [44]:
def itoa(t):
    ret = head_neg = ""
    
    if (-t) > 0:
        head_neg = "-"
        t = -t
    
    while (t > 1):        
        r = (t % 10)                 
        t = t  / 10
        ret = chr(48+int(r)) + ret
      
    return head_neg+ret
    #print (n)

    
print ("the number is %s" % itoa(1947))
print ("the number is %s" % itoa(-1947))


the number is 1947
the number is -1947

atoi


In [85]:
int_char = {"0", "1", "2", "3", "4", "5", "6", "7","8","9"}

def myAtoi(s):
    """
    :type str: str
    :rtype: int
    """
    if not s:
        return 0

    sign = 1
    ret = 0

    # Remove training 0, check for a + or - sign followed by an integer character
    s = s.strip()
    if s[0]=="-":
        sign = -1
        s = s[1:]

    elif s[0]=="+":
        sign = 1
        s = s[1:]

    if not s or s[0] not in int_char:
        return 0

    # Get all valid consecutive integers
    out = []
    for i, v in enumerate(s):
        if v in int_char:
            out.append(v)
        else:
            break

    for i,v in enumerate(out[::-1]):
        ret += int(v)* 10**i

    if sign == 1 and ret > 2147483647:
        ret = 2147483647
    elif sign == -1 and ret > 2147483648:
        ret = 2147483648

    return sign * ret

In [86]:
val = myAtoi("  -123  ")
assert val == -123, "wrong value {} expected {}".format(val, -123)

val = myAtoi("-23ab3")
assert val == -23, "wrong value {} expected {}".format(val, -23)

val = myAtoi("-00233")
assert val == -233, "wrong value {} expected {}".format(val, -233)

val = myAtoi("  - 233")
assert val == 0, "wrong value {} expected {}".format(val, 0)

val = myAtoi("  -2a33")
assert val == -2, "wrong value {} expected {}".format(val, -2)

val = myAtoi("  -0012a42")
assert val == -12, "wrong value {} expected {}".format(val, 12)

print ("All test passed")


All test passed

In [ ]: