Advertisement
Guest User

Untitled

a guest
Apr 5th, 2020
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.08 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <malloc.h>
  3. #include <string.h>
  4.  
  5. char* int_to_string(const unsigned long a) {
  6.     long temp = a;
  7.     int length = 0;
  8.     while (temp > 10) {
  9.         temp /= 10;
  10.         length++;
  11.     }
  12.  
  13.     char* string = calloc(length, sizeof(char));
  14.     sprintf(string, "%lu", a);
  15.     return string;
  16. }
  17.  
  18. unsigned long calc_digit_sum(const char* string, int length) {
  19.     unsigned long sum = 0;
  20.     for (int i = 0; i < length; i++)
  21.         sum += string[i] - 0x30;
  22.     return sum;
  23. }
  24.  
  25. int main() {
  26.     char number[1024] = {0};
  27.     char read = 1;
  28.     int length = 0;
  29.  
  30.     while(((int)read) > 0) {
  31.         scanf("%c", &read);
  32.         if(read == '\n')
  33.             break;
  34.         length++;
  35.         number[length - 1] = read;
  36.     }
  37.  
  38.     unsigned long digit_sum = calc_digit_sum(number, length);
  39.  
  40.     while(digit_sum > 9) {
  41.         char* dgsm = int_to_string(digit_sum);
  42.         int dgsm_length = strlen(dgsm);
  43.  
  44.         digit_sum = calc_digit_sum(dgsm, dgsm_length);
  45.         free(dgsm);
  46.     }
  47.     printf("%d", digit_sum);
  48.     free(number);
  49.     return 0;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement