HomeInterview QuestionsHow would you mask a 16‑digit credit card number t…

How would you mask a 16‑digit credit card number to display only the last four digits, and how would you handle cases where the number is shorter or longer than 16 digits or contains non‑numeric characters?

🟡 Medium Coding Junior level
1Times asked
Sep 2026Last seen
Sep 2026First seen

💡 Model Answer

To mask a 16‑digit credit card number and show only the last four digits, you can use a simple string manipulation approach. First, validate the input: ensure it contains only digits and is exactly 16 characters long. If the length is less than 16, you can pad it with leading zeros or return an error; if it is longer, truncate or flag an error. If non‑numeric characters are present, strip them or reject the input. Once validated, you can build the masked string by concatenating a fixed mask (e.g., '** ') with the last four digits: masked = ' ** ' + card[-4:]. In Java, you might use String.format or StringBuilder; in Python, f'{card[-4:]}'. For robustness, wrap the logic in a function that returns a tuple (is_valid, masked_value) so callers can handle invalid inputs gracefully. This approach ensures compliance with PCI‑DSS masking rules and protects sensitive data while still allowing the user to identify the card. If you need to mask multiple cards in a batch, you can vectorize the operation using list comprehensions or map functions, and log any anomalies for audit purposes. Remember to never log the full card number; only the masked representation should be stored or displayed. This simple pattern is widely used in payment gateways, mobile wallets, and e‑commerce checkout flows.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI — Starts at ₹500