๐Ÿ‘ฉ‍๐Ÿ’ป ์•Œ๊ณ ๋ฆฌ์ฆ˜/๐Ÿข PYTHON

๊ฐ ์ž๋ฆฟ์ˆ˜ ํ•ฉ ๊ตฌํ•˜๊ธฐ

์˜ค๋ธŒ ๐Ÿง™‍โ™‚๏ธ 2023. 9. 16. 02:55

 

# sum_digit ํ•จ์ˆ˜ ์ •์˜
def sum_digit(num):
    # ๊ฐ ์ž๋ฆฟ์ˆ˜์˜ ํ•ฉ์„ ์ €์žฅํ•  ๋ณ€์ˆ˜๋ฅผ ์ดˆ๊ธฐํ™”ํ•ฉ๋‹ˆ๋‹ค.
    total = 0
    
    # num์ด 0๋ณด๋‹ค ํด ๋™์•ˆ ๋ฐ˜๋ณตํ•ฉ๋‹ˆ๋‹ค.
    while num > 0:
        # num์„ 10์œผ๋กœ ๋‚˜๋ˆˆ ๋‚˜๋จธ์ง€๋ฅผ ๊ตฌํ•ด์„œ ๊ฐ ์ž๋ฆฟ์ˆ˜๋ฅผ ์–ป์Šต๋‹ˆ๋‹ค.
        digit = num % 10
        
        # ๊ฐ ์ž๋ฆฟ์ˆ˜๋ฅผ total์— ๋”ํ•ฉ๋‹ˆ๋‹ค.
        total += digit
        
        # num์„ 10์œผ๋กœ ๋‚˜๋ˆ  ํ•œ ์ž๋ฆฟ์ˆ˜์”ฉ ์ค„์ž…๋‹ˆ๋‹ค.
        num = num // 10
        
    # ์ตœ์ข…์ ์œผ๋กœ ๊ฐ ์ž๋ฆฟ์ˆ˜์˜ ํ•ฉ์ธ total์„ ๋ฆฌํ„ดํ•ฉ๋‹ˆ๋‹ค.
    return total

# sum_digit(1)๋ถ€ํ„ฐ sum_digit(1000)๊นŒ์ง€์˜ ํ•ฉ์„ ๊ตฌํ•ฉ๋‹ˆ๋‹ค.
result = 0
for i in range(1, 1001):
    result += sum_digit(i)

# ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.
print("sum_digit(1)๋ถ€ํ„ฐ sum_digit(1000)๊นŒ์ง€์˜ ํ•ฉ:", result)
def sum_digit(num):
    total = 0
    str_num = str(num)
    
    for digit in str_num:
        total += int(digit)

    return total

print(sum_digit(34))
#์ถœ๋ ฅ๊ฐ’ 7