NetEase School Recruitment - Magic Coin Problem

magic coins

Time limit: 1 second

Space limitation: 32768K Xiaoyi
is going to go to the Magic Kingdom to purchase magic artifacts. To buy magic artifacts, you need to use magic coins, but Xiaoyi doesn't have a single magic coin now, but Xiaoyi has two magic machines. You can use x (x can be 0) ) magic coins generate more magic coins.
Magic Machine 1: If you put in x Magic Coins, the Magic Machine will turn it into 2x+1 Magic Coins
Magic Machine 2: If you put in x Magic Coins,
the Magic Machine will turn it into 2x+2 Magic Coins A total of n magic coins are needed to purchase magic artifacts, so Xiaoyi can only generate exactly n magic coins through two magic machines. Xiaoyi needs you to help him design an investment plan so that he has exactly n magic coins in the end.
Enter description:

The input consists of one line, including a positive integer n (1 ≤ n ≤ 10^9), which represents the number of magic coins Xiaoyi needs.

Output description:
Output a string, each character represents the magic machine that Xiaoyi selects and invests in. which only contains the characters '1' and '2'.

Input Example 1:
10

Output example 1:
122


Problem- solving idea: Use the target value inversion scheme Design(n)
to judge the target value. If the target value is odd, use the magic machine 1 to push back, if it is an even number, use the magic machine 2 to push back, each time Reverse push to obtain a new target value, and
repeat the above operations for the new target value until the target value is 0

The string obtained after the reverse push is in reverse order. At this time, the obtained string PrintStr(str) needs to be output in reverse order.


The Python3.5 code is as follows:

def Design(n):
    str=''
    while n:
        if n%2==0:
            str=str+"2"
            n=(n-2)//2 
        else:
            str=str+"1"
            n=(n-1)//2
    return str

def PrintStr(str):
    ptr=len(str)
    while ptr:
        print(str[ptr-1],end='')
        ptr=ptr-1

def main():
    n = eval(input())  
    str=Design(n)
    PrintStr(str)


main()

The running result is:
write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325395657&siteId=291194637