簡単 1件解決済み 正答率100.0%

Reverse a Number

Reverse the decimal digits of a positive integer.

このチャレンジで学べること

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

問題

翻訳を表示

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.

例

例 1
入力:
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.

例 2
入力:
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 つずつ開いてみましょう。

ヒント 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

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

# コーダー 言語 時間 メモリ AI 評価 解答
1 KKKaneki Ken Python 982 ms - 5/5 コードを見る

他の人の解答から学ぶ

コミュニティの解答

ネタバレ注意:下に1件の全解答あり まずは自分で挑戦してみましょう。他の開発者のコードやAIレビューも見ることができます。 サインインして課題を解くと議論に参加できます。