Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Swap the First and Last Digits of a Number

Basic Acceptance 78.12% Points 10.00

You are given a non-negative integer n. Your task is to return the number formed by swapping its first and last digits, while keeping all the digits in between in their original order.

If the number contains only one digit, return it unchanged.

Examples
Example 1

Input: n = 1234
Output: 4231
Explanation: The first digit, 1, and the last digit, 4, are exchanged, producing 4231.

Example 2

Input: n = 5005
Output: 5005
Explanation: The first and last digits are both 5, so swapping them leaves the number unchanged.

Example 3

Input: n = 7
Output: 7
Explanation: A single-digit number has the same first and last digit, so it remains unchanged.

Constraints
  • 0 = n = 10?
Companies
Microsoft J.P. Morgan Qualcomm
Topics
Data Structures Basics String
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions