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
2
Output
12
56
Explanation

For N=123456 and X=2, the first 2 digits are '12' and the last 2 digits are '56'

Example 2
Input
00010245699
3
Output
102
699
Explanation

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:

  1. Declares a character array of size 21 to store the number string
  2. Uses fgets() to read the number as a string, preserving leading zeros
  3. Removes the newline character using strcspn()
  4. Reads X using scanf()
  5. Uses a loop to print the first X characters
  6. Uses another loop to print the last X characters starting from position (length - X)

Visual Explanation

Loading diagram...