Skip to content

ORIGINAL CODING QUESTION

Digit-square convergence

Repeatedly replace a positive integer with the sum of squares of its decimal digits. Print 1 if this reaches 1, otherwise 0 when a cycle repeats.

Open practice workspace

Original exercise · easy. Editorial role relevance does not imply a company has asked this question.

Input and output

One positive integer x.

Constraints

1 ≤ x ≤ 1000000000.

Example 1

Input

19

Output

1

19→82→68→100→1.

Example 2

Input

2

Output

0

The sequence enters a cycle that excludes 1.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

The sequence eventually reaches a previously visited state or one.

Hint 2

A set detects repeats.

Hint 3

Fast/slow state transitions can detect a cycle without a set.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →