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 unsigned long a) {
- long temp = a;
- int length = 0;
- while (temp > 10) {
- temp /= 10;
- length++;
- }
- char* string = calloc(length, sizeof(char));
- sprintf(string, "%lu", a);
- return string;
- }
- unsigned long calc_digit_sum(const char* string, int length) {
- unsigned long sum = 0;
- for (int i = 0; i < length; i++)
- sum += string[i] - 0x30;
- return sum;
- }
- int main() {
- char number[1024] = {0};
- char read = 1;
- int length = 0;
- while(((int)read) > 0) {
- scanf("%c", &read);
- if(read == '\n')
- break;
- length++;
- number[length - 1] = read;
- }
- unsigned long 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);
- free(dgsm);
- }
- printf("%d", digit_sum);
- free(number);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement