Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
483 views
in Technique[技术] by (71.8m points)

algorithm - Obfuscated code: last digit

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:

+[>,]<.>++++++++++.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...