Skip to content

Problem 8: Remove Digits at Even Positions (100pts)

Problem

Write a function that takes a number, removes the digits in even positions (the 2nd, 4th, 6th, … from left to right), and returns the number formed by the remaining digits.

Warning:

You should not use data structures like lists or strings, or converting from other data structures to int using int(...) in this problem.

Violating this requirement may result in a loss of scores in online judge testing.

编写一个函数,接受一个数字作为参数,移除处于偶数位置的数字(从左到右数第 2 位、第 4 位、第 6 位等),并返回由剩余数字组成的新数字。

Warning

在本问题中,您不应使用列表或字符串等数据结构,也不应使用 int(...) 将其他数据结构转换回整数。

违反此要求可能导致在线判题测试失分。

def remove_even_position(n):
    """Removes the digits of n in even positions (the 2nd, 4th, 6th, … from left to right),
    and returns the number formed by the remaining digits.

    >>> remove_even_position(0)
    0
    >>> remove_even_position(10)
    1
    >>> remove_even_position(123)
    13
    >>> remove_even_position(123456)
    135
    """
    "*** YOUR CODE HERE ***"

Hints

  • 本来可以用 str 切片逃课的但是被制裁了...

  • 可以尝试获取所有奇数位的数然后拼在一起。必要时可以将数反向

  • 可以先获取 n 的位数(math.log(n, 10)math.log10(n) 是一种选择?),然后依次获取每一个奇数位的数

Solutions

先算出 \(n\) 有几位,再遍历 \(n\) 的每一位

def remove_even_position(n):
    x = 1
    p = 0
    #找到最小的 p, 使 n < 10 ** p,则 n 的位数为 p(假设 0 的位数为 0 )
    while(n >= x):
        p += 1
        x *= 10     #使 x 等于 10 ** p

    m = 0   #构造一个新数字
    l = 1
    # 遍历 n 的第 l 位
    while(l <= p):
        x //= 10    #使 x 最高位的 1 对齐第 l 位
        if(l % 2 == 1): m = m * 10 + n // x     #若当前为奇数位,在 m 的末尾加入这一位
        n %= x      #去掉 n 的首位
        l += 1
    return m

Generated by AI.

先用 while 循环获取 n 的位数,然后从左至右一次获取每一位。这里使用一个变量跟踪位置,一个变量获取每一位。

def remove_even_position(n):
    if n == 0:
        return 0

    # 1. Determine the length (number of digits)
    length = 0
    temp = n
    # Count the number of times we can divide by 10
    while temp > 0:
        temp //= 10
        length += 1

    # 2. Iterate from the leftmost digit
    final_result = 0
    temp = n

    # Start with the power of 10 for the leftmost digit's place value
    # E.g., for 123456 (length 6), start with 10^5 = 100000
    power_of_10 = 10 ** (length - 1)

    current_position = 1  # Tracks the position from the LEFT (1st, 2nd, 3rd, ...)

    while power_of_10 >= 1:
        # Get the leftmost digit
        digit = temp // power_of_10

        # We KEEP the digits in ODD positions (1st, 3rd, 5th, ... from the left)
        if current_position % 2 != 0:
            # Build the new number from left to right
            final_result = final_result * 10 + digit

        # Remove the leftmost digit from temp
        temp %= power_of_10

        # Advance to the next position/place value
        power_of_10 //= 10
        current_position += 1

    return final_result

也可以使用 math.log10 获取 n 的位数:

import math
length = math.floor(math.log10(n)) + 1

只用一个 while 循环。先从右向左获取奇数位和偶数位,根据长度决定留下哪一个

def remove_even_position(n):
    if n == 0:
        return 0

    # These variables are initialized before the single main loop
    result_odd_from_right = 0    
    result_even_from_right = 0   

    multiplier_odd = 1
    multiplier_even = 1
    digit_count = 1  # Tracks the position from the RIGHT (1st, 2nd, 3rd, ...)
    temp = n         # The number we will process

    # 1. Single Main Loop: Counts length AND builds two numbers
    while temp > 0:
        digit = temp % 10

        # Build the two candidate results
        if digit_count % 2 != 0:
            # ODD position from the RIGHT
            result_odd_from_right += digit * multiplier_odd
            multiplier_odd *= 10
        else:
            # EVEN position from the RIGHT
            result_even_from_right += digit * multiplier_even
            multiplier_even *= 10

        temp //= 10
        digit_count += 1

    # Note:
    length = digit_count - 1

    # 2. Decision Phase: Use the final length to decide which result to use.
    # We want the ODD positions from the LEFT.
    # - If LENGTH is ODD (e.g., 12345): The correct one is result_odd_from_right.
    # - If LENGTH is EVEN (e.g., 123456): The correct one is in result_even_from_right.

    if length % 2 != 0: 
        return result_odd_from_right
    else:               
        return result_even_from_right

str 切片()

def remove_even_position(n):
    return int(str(n)[::2])