Nice to meet you. I'm Koizumi from the Development Department.
In this article, I will explain how to make 0-10 without using numbers in PHP.
first of all
echo true will output "1".
It occurred to me that I could use this to create other numbers without using any numbers at all, so I tried it out.
It's not interesting to just make one, so I added the following restrictions.
1. type must be int (confirmed by var_dump)
2. be as short as possible
3. don't use constants (because it's too easy)
If you know PHP, please try to predict what the code will be.
If you want to test whether the code in the text is correct, you can easily try it by copying and pasting it into the following site.
1 and 0
I indicated at the beginning
echo true looks like 1, but internally it is of type bool.
You'll need to cast it to an int, but you can use the commonly-used
intval()is long, so the operator + is used.
Also, "true" is 4 characters long, so you can shorten it to 3 characters by adding "(empty string)" and "! to shorten it to 3 characters.
You can create false as well and cast it to int to create 0 as well.
The result is the following code.
var_dump(+!'') ; //0 var_dump(+!'') ; //1
2 is not 1+1, but the bitwise negation operator
~to make it.
It's complicated, so I won't explain it, but bitwise negating an integer n results in -(n+1). (If you are curious, please look it up in 2's complement)
The sign can be reversed by adding a -, so
-~can "cast a positive number to an int and add one".
This is a frequent technique, so please keep it in mind.
var_dump(-~+!'') ; //2
Pi (3 to 5)
Speaking of 3, Pi.
pi()I know. As it is, it is a float type and becomes 3.14... so cast it to int.
The bitwise operators will cast to int, so
~~You can truncate by putting two bit negations in a row, such as
By combining pi and bit negation, we can make 3 to 5.
var_dump(~~pi()); //3 var_dump(-~pi()); //4 var_dump(-~-~pi()); //5
Bit shift (6 to 9)
6 is twice as many as 3. Normally, we use *, but 2(
-~+!'') is six characters long, so instead we use the bit shift
Since we are going to multiply by a power of 2, 6 is
3<<1, 8 is
1<<3can be represented respectively by
For 7 and 9, we just need to make 6 and 8 each one bigger.Operator precedenceso you need to enclose it in parentheses.
10 is a in hexadecimal and can be expressed without using numbers.
Unlike the past, I think the code is easy to read.var_dump(hexdec('a')); //10
Finally, I'll restate the code so far.var_dump(+!'') ; //0 var_dump(+!'') ; //1 var_dump(-~+!'') ; //2 var_dump(~~pi()); //3 var_dump(-~pi()); //4 var_dump(-~-~pi()); //5 var_dump(pi()<
The readability of the code would have been very poor.
It also gave me a chance to learn more about things I'm not usually aware of, such as bit negation and operator precedence.
It's interesting to exercise your mind when you think about something completely different from the usual programming like this.