โจทย์
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.
เงื่อนไข
1 ≤ n ≤ 10¹⁸. The reversed value always fits a signed 64-bit integer.
ตัวอย่าง
อินพุต:
n = 352
ผลลัพธ์ที่คาดหวัง:
expected = 253
อินพุต:
long long n = 352;
ผลลัพธ์ที่คาดหวัง:
long long expected = 253;
อินพุต:
long n = 352;
ผลลัพธ์ที่คาดหวัง:
long expected = 253;
คำอธิบาย
The digits 3, 5, 2 reversed are 2, 5, 3.
อินพุต:
n = 1200
ผลลัพธ์ที่คาดหวัง:
expected = 21
อินพุต:
long long n = 1200;
ผลลัพธ์ที่คาดหวัง:
long long expected = 21;
อินพุต:
long n = 1200;
ผลลัพธ์ที่คาดหวัง:
long expected = 21;
คำอธิบาย
Reversed digits are 0021; leading zeros are dropped, giving 21.
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
The key is to build the result one digit at a time from the end of the number.
คำใบ้ 2
Use repeated remainder and division to extract digits in reverse order.
คำใบ้ 3
Leading zeros in the reversed form should disappear naturally, so be careful not to preserve them.
ความซับซ้อนที่คาดหวัง
O(d) time, O(1) extra space