Skip to content

S1Q3 · Shuffle Digits

⚡ Quick Reference

Function: shuffle_digits(num: int) -> int

Core idea: Convert to string, pick digits by position in the required order, convert back to int.

def shuffle_digits(num):
    s = str(num)
    return int(s[1] + s[3] + s[0] + s[2])

Key rules: - Positions are 0-indexed: s[0] = 1st digit, s[1] = 2nd, etc. - New order is digit 2, digit 4, digit 1, digit 3 → indices [1, 3, 0, 2] - Return an int, not a string


Problem Statement

Problem

Write a function shuffle_digits(num) that takes a 4-digit positive integer and rearranges its digits in the order 2-4-1-3: the 2nd digit becomes 1st, 4th becomes 2nd, 1st becomes 3rd, 3rd becomes 4th.

Examples:

Call
shuffle_digits(1234)
Output
2413
Call
shuffle_digits(2413)
Output
4321

Understanding the problem

The shuffle maps each position to a new one. Using 1-based positions as stated in the problem, then converting to 0-based string indices:

New position Takes digit from 1-based pos 0-based index
1st 2nd digit 2 s[1]
2nd 4th digit 4 s[3]
3rd 1st digit 1 s[0]
4th 3rd digit 3 s[2]

Trace with 1234:

Digit d1=1 d2=2 d3=3 d4=4
New order pos 3 pos 1 pos 4 pos 2
Result 2 4 1 3

Output: 2413 ✅

The four examples form a cycle

1234 → 2413 → 4321 → 3142 → 1234. Applying the shuffle four times brings you back to the original number. This is a useful self-check: call the function four times on any input and verify you get the original back.


Solution approaches

def shuffle_digits(num: int) -> int:
    s = str(num)          # "1234"
    d1, d2, d3, d4 = s[0], s[1], s[2], s[3]
    # new order: 2nd, 4th, 1st, 3rd
    shuffled = d2 + d4 + d1 + d3
    return int(shuffled)
def shuffle_digits(num: int) -> int:
    s = str(num)
    return int(s[1] + s[3] + s[0] + s[2])
shuffle_digits = lambda num: int((s := str(num)) and s[1] + s[3] + s[0] + s[2])

Key takeaways

01

String indexing for digit access

Converting to a string with str(num) makes each digit individually addressable by index. This is simpler than arithmetic extraction (// 10, % 10) when rearranging digits in arbitrary order.

02

1-based to 0-based index translation

Problem statements describe positions starting from 1 ("2nd digit"), but Python strings are 0-indexed. Subtract 1: position 2 → s[1], position 4 → s[3]. Always do this translation explicitly before writing the code.

03

String concatenation then int()

Build the result as a string by concatenating individual character digits, then wrap in int() to return the correct type. Leading zeros (e.g. if the 2nd digit is 0) are automatically dropped by int().