Сценарий оболочки Bash для поиска суммы цифр
Опубликовано: 16 Февраля, 2022
Учитывая число Num, найдите сумму цифр числа.
Примеры:
Вход : 444 Выход : сумма цифр 444 составляет: 12 Вход : 34 Выход : сумма цифр 34 составляет: 7
Рекомендуется: сначала попробуйте свой подход в {IDE}, прежде чем переходить к решению.
Approach:
1. Divide the number into single digits 2. Find the sum of digits .
Bash
# !/bin/bash # Program to find sum# of digits # Static input of the# numberNum=123g=$Num # store the sum of # digitss=0 # use while loop to# caclulate the sum# of all digitswhile [ $Num -gt 0 ]do # get Remainder k=$(( $Num % 10 )) # get next digit Num=$(( $Num / 10 )) # calculate sum of # digit s=$(( $s + $k )) doneecho "sum of digits of $g is : $s" |
Output
sum of digits of 123 is : 6