Kaze79

cs50 credit

Oct 12th, 2023 (edited)
1,187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.19 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4.  
  5. int addAllDigits(char digits[], int doubleTheDigit) {
  6.     int length = sizeof(digits)/sizeof(digits[0]);
  7.     int finalSum = 0;
  8.     for(int i = 0; i < length; i++) {
  9.         int digit;
  10.         if(doubleTheDigit == 1) {
  11.             digit = (digits[i] - '0')*2;
  12.         } else {
  13.             digit = digits[i] - '0';
  14.         }
  15.         if(digit >= 10) {
  16.             digit = digit/10 + digit%10;
  17.         }
  18.         finalSum += digit;
  19.     }
  20.    
  21.     return finalSum;
  22. }
  23.  
  24. int main() {
  25.     char cardNumber[] = "4003600000000014";
  26.    
  27.     int length = strlen(cardNumber);
  28.    
  29.     char digits2double[20];
  30.     int digitIndex = 0;
  31.     for(int cardIndex = length-2; cardIndex >= 0; cardIndex -= 2) {
  32.         digits2double[digitIndex] = cardNumber[cardIndex];
  33.         digitIndex++;
  34.     }
  35.     int doubledSum = addAllDigits(digits2double, 1);
  36.    
  37.     char digits[20];
  38.     digitIndex = 0;
  39.     for(int cardIndex = length-1; cardIndex >= 0; cardIndex -= 2) {
  40.         digits[digitIndex] = cardNumber[cardIndex];
  41.         digitIndex++;
  42.     }
  43.     int sum = addAllDigits(digits, 0);
  44.    
  45.     printf("--> %d + %d = %d\n", doubledSum, sum, doubledSum + sum);
  46. }
  47.  
Advertisement
Add Comment
Please, Sign In to add comment