easy
1 views

Sum of Last X Digits

Given two integers N and X, compute the sum of the last X digits of the integer N.

Understand the Problem

Problem Statement

Given two integers N and X as input, the program must print the sum of last X digits in the given integer N.

Constraints

  • 1 ≤ N ≤ 999999999999999
  • 1 ≤ X ≤ 15
  • N must be a valid integer
  • X must be a valid integer

Examples

Example 1
Input
28634
3
Output
13
Explanation

Last 3 digits of 28634 are 6, 3, 4. Sum = 6 + 3 + 4 = 13.

Example 2
Input
147173
2
Output
10
Explanation

Last 2 digits of 147173 are 7, 3. Sum = 7 + 3 = 10.

Solution

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main() {
    char N[20];  // Large enough to hold 15 digits plus null terminator
    int X;
    
    // Read input
    scanf("%s", N);
    scanf("%d", &X);
    
    int len = strlen(N);
    int sum = 0;
    
    // Calculate how many digits to sum (handle case where X > length of N)
    int digits_to_sum = (X < len) ? X : len;
    
    // Sum the last X digits
    for (int i = len - digits_to_sum; i < len; i++) {
        if (isdigit(N[i])) {
            sum += N[i] - '0';  // Convert char to int
        }
    }
    
    printf("%d\n", sum);
    
    return 0;
}
Time:O(X) - We iterate through at most X digits
Space:O(1) - We use a fixed-size array and a few variables
Approach:

Step-by-step explanation:

  1. Declare a character array to store the large number as string
  2. Read N as string and X as integer using scanf
  3. Get the length of the string representation
  4. Calculate how many digits to sum (minimum of X and string length)
  5. Loop through the last X characters of the string
  6. Convert each character digit to integer by subtracting '0'
  7. Accumulate the sum
  8. Print the result

Visual Explanation

Loading diagram...