Dễ 1 đã giải Tỷ lệ chấp nhận 100.0%

Reverse a Number

Reverse the decimal digits of a positive integer.

Bạn sẽ học được gì

  • Take digits off the end of a number one by one
  • Build a new number by shifting digits left (× 10)
  • Handle trailing zeros correctly

Đề bài

Xem bản dịch

Write the decimal digits of n in reverse order and return the resulting number. Zeros that end up at the front disappear, so 1200 becomes 21.

Implement reverse_number(n).

Input

n: A positive integer.

Output

Return the reversed number.

Ràng buộc

1 ≤ n ≤ 10¹⁸. The reversed value always fits a signed 64-bit integer.

Ví dụ

Ví dụ 1
Đầu vào:
n = 352

Kết quả mong đợi:
expected = 253
Đầu vào:
long long n = 352;

Kết quả mong đợi:
long long expected = 253;
Đầu vào:
long n = 352;

Kết quả mong đợi:
long expected = 253;

Giải thích

The digits 3, 5, 2 reversed are 2, 5, 3.

Ví dụ 2
Đầu vào:
n = 1200

Kết quả mong đợi:
expected = 21
Đầu vào:
long long n = 1200;

Kết quả mong đợi:
long long expected = 21;
Đầu vào:
long n = 1200;

Kết quả mong đợi:
long expected = 21;

Giải thích

Reversed digits are 0021; leading zeros are dropped, giving 21.

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

The key is to build the result one digit at a time from the end of the number.

Gợi ý 2

Use repeated remainder and division to extract digits in reverse order.

Gợi ý 3

Leading zeros in the reversed form should disappear naturally, so be careful not to preserve them.

Độ phức tạp mong đợi

O(d) time, O(1) extra space

Lời giải đạt tốt nhất của mỗi người. Lời giải nhanh hơn, tốn ít bộ nhớ hơn và được đánh giá cao hơn sẽ đứng trên.

# Người giải Ngôn ngữ Thời gian Bộ nhớ AI đánh giá Lời giải
1 KKKaneki Ken Python 982 ms - 5/5 Xem code

Học hỏi từ người khác

Giải pháp cộng đồng

Cảnh báo: Có 1 lời giải đầy đủ bên dưới Hãy thử tự giải trước. Bạn vẫn có thể xem mã của người khác và đánh giá AI. Đăng nhập và giải thử thách để tham gia thảo luận.