easy
0 views
First and Last X Digits
Extract and print the first X digits and last X digits from a given number N
Understand the Problem
Problem Statement
Given a number N and an integer X, print the first X digits and the last X digits of the number N.
The number N can have leading zeros, but these should be preserved when extracting the digits.
Constraints
- 1 ≤ X ≤ 20
- 1 ≤ Length of N ≤ 20
- X ≤ Length of N
- N can contain leading zeros
- N is a non-negative integer
Examples
Example 1
Input
123456
2Output
12
56Explanation
For N=123456 and X=2, the first 2 digits are '12' and the last 2 digits are '56'
Example 2
Input
00010245699
3Output
102
699Explanation
For N=00010245699 and X=3, the first 3 digits are '102' (ignoring leading zeros) and the last 3 digits are '699'
Solution
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char n[21]; // Maximum length is 20
int x;
// Read the number as string to preserve leading zeros
fgets(n, sizeof(n), stdin);
n[strcspn(n, "\n")] = 0; // Remove newline
scanf("%d", &x);
int len = strlen(n);
// Print first X digits
for (int i = 0; i < x; i++) {
printf("%c", n[i]);
}
printf("\n");
// Print last X digits
for (int i = len - x; i < len; i++) {
printf("%c", n[i]);
}
printf("\n");
return 0;
}Time:O(X) - We iterate through at most 2X characters to print the results
Space:O(1) - Only using a fixed-size array and a few variables
Approach:
The C solution:
- Declares a character array of size 21 to store the number string
- Uses fgets() to read the number as a string, preserving leading zeros
- Removes the newline character using strcspn()
- Reads X using scanf()
- Uses a loop to print the first X characters
- Uses another loop to print the last X characters starting from position (length - X)
Visual Explanation
Loading diagram...