Advertisement
Guest User

Untitled

a guest
Apr 4th, 2020
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.91 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <malloc.h>
  3. #include <string.h>
  4.  
  5. char* int_to_string(const int a) {
  6.     int 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, "%d%c", a, 0);
  15.     return string;
  16. }
  17.  
  18. int calc_digit_sum(const char* string, int length) {
  19.     int sum = 0;
  20.     for (int i = 0; i < length; i++)
  21.         sum += string[i] - 0x30;
  22.     return sum;
  23. }
  24.  
  25. int main() {
  26.     int in_number;
  27.     scanf("%d", &in_number);
  28.  
  29.  
  30.     char* number = int_to_string(in_number);
  31.     int length = strlen(number);
  32.     int digit_sum = calc_digit_sum(number, length);
  33.  
  34.     while(digit_sum > 9) {
  35.         char* dgsm = int_to_string(digit_sum);
  36.         int dgsm_length = strlen(dgsm);
  37.  
  38.         digit_sum = calc_digit_sum(dgsm, dgsm_length);
  39.  
  40.     }
  41.  
  42.     printf("%d", digit_sum);
  43.  
  44.     return 0;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement