Obfuscated code: last digit

2019-09-25 07:47发布

问题:

I have a challenge to write obfuscated code in the brainfuck language to do the following:

For a given number n output its last digit.

input

Input will consist of only one line in which there is only one integer n ( 1 < = n < = 2,000,000,000 ) , followed by a newline ' \ n' (ASCII 10).

output

On the output, has to find exactly one integer denoting the last digit of n.

example I input: 32 output: 2

example II: input: 231231132 output: 2

This is what I tried, but it didn't work:

+[>,]<.>++++++++++.

回答1:

The problem is that you're telling the loop to terminate when the input is 0.

The input is never 0, the ASCII for newline is 10 so that's what you'll need to use.

This code should work. In reality, this code doesn't care at all if you've given it a number, it just returns the last character before the first newline it finds.

+[     // increment [1] by 1 and enter the loop
  ,[     // read input to [1] and enter another loop
     >+>+<<-     // copy the initial input twice whilst decrementing the original
  ]
  >>>++++++++++     // write 10 (for newline) and enter a loop
  [
    <->-     // decrement the 10 counter and one of the copied inputs
  ]
< step back to the (input - 10) cell
]<<<.     // if (input - 10 == 0) then you just read a carriage return! yay! Step back by three to the last stored input and print it out to the console.