简体   繁体   中英

Method to square every digit of an int not working

def square_digits(num):
    x = 0
    for i in str(num):
        y = int(i) * int(i)
        x += y 
    return x

The above code is supoose to square every digit of an integer and concatenate it that is passed in but it doesnt do that. I ran the belpow code and it gives the output 164.

square_digits(9119)

If you want it to output 811181 , you need to change x to a string:

def square_digits(num):
    x = ''
    for i in str(num):
        y = int(i) * int(i)
        x += str(y) 
    return x

It's answer is True:
9*9 + 1*1 + 1*1 + 9*9 = 81 + 1 + 1 + 81 =164

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM