Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <malloc.h>
- #include <string.h>
- char* int_to_string(const int a) {
- int temp = a;
- int length = 0;
- while (temp > 10) {
- temp /= 10;
- length++;
- }
- char* string = calloc(length, sizeof(char));
- sprintf(string, "%d%c", a, 0);
- return string;
- }
- int calc_digit_sum(const char* string, int length) {
- int sum = 0;
- for (int i = 0; i < length; i++)
- sum += string[i] - 0x30;
- return sum;
- }
- int main() {
- int in_number;
- scanf("%d", &in_number);
- char* number = int_to_string(in_number);
- int length = strlen(number);
- int digit_sum = calc_digit_sum(number, length);
- while(digit_sum > 9) {
- char* dgsm = int_to_string(digit_sum);
- int dgsm_length = strlen(dgsm);
- digit_sum = calc_digit_sum(dgsm, dgsm_length);
- }
- printf("%d", digit_sum);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement