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
3Output
13Explanation
Last 3 digits of 28634 are 6, 3, 4. Sum = 6 + 3 + 4 = 13.
Example 2
Input
147173
2Output
10Explanation
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:
- Declare a character array to store the large number as string
- Read N as string and X as integer using scanf
- Get the length of the string representation
- Calculate how many digits to sum (minimum of X and string length)
- Loop through the last X characters of the string
- Convert each character digit to integer by subtracting '0'
- Accumulate the sum
- Print the result
Visual Explanation
Loading diagram...