If you are looking for the nearest value problem, please give your mind to do something. The value of A is known and B needs to be found. The value of B is the number of records smaller than A and 2. For example, if A765 requires B, B is equal to 512. I think of A way, because the value of A has the maximum range, so I put 2 to the power of 1, 2 to the power of 2, 2 to the power of three ...., are saved as an array, and then use the value to compare with this array to find the B value that meets the requirements. However, I think there should be other better methods. please give me some advice. Thank you for finding the nearest value. please give me some advice.
To do something, the value of A is known, and B needs to be found. The value of B is the number of workers smaller than A and 2.
For example, if A = 765 and B is required, B is equal to 512. I think of A way, because the value of A has the maximum range, so I put 2 to the power of 1, 2 to the power of 2, 2 to the power of three ...., are saved as an array, and then use the value to compare with this array to find the B value that meets the requirements.
However, I think there should be other better methods. please give me some advice. Thank you!
------ Solution --------------------
Function get2str ($ n)
{
$ Len = strlen (decbin ($ n ));
$ Str2 = '1'. str_repeat ('0', $ len-1 );
Return bindec ($ str2 );
}
Var_dump (get2str (578 ));
// Int (512)
The idea is as follows:
4: 100 3
8: 1000 4
16: 10000 5
32: 100000 6
64: 1000000 7
128: 10000000 8
256: 100000000 9
512: 1000000000 10
1024: 10000000000 11
2048: 100000000000 12
578: 1001000010 10
As you can see, they are decimal numbers: binary string length
The 578 and 512 binary strings are 10 bytes long. I do not know PHP bit operations, so I think there must be a more efficient and simple solution.
------ Solution --------------------
Review the index and logarithm.
PHP code
$ A = 765; echo pow (2, floor (log ($ a, 2 )));
------ Solution --------------------
1. keep the leftmost 1. bitwise operation.
PHP code
[[Email protected] php_project] $ php main. php 765 => 5120 => 0256 => 2561 => 13 => 2255 => 128257 => 256 [[email protected] php_project] $ cat main. php
> $ Off )! = 1) {++ $ off;} return 1 <$ off ;}}$ cases = array (765, 0,256, 2.3, 1, 3,255,257 ); foreach ($ cases as $ value) {if ($ ret = bit_alg ($ value ))! = False) {echo $ value. "=>". $ ret. PHP_EOL ;}}?>
------ Solution --------------------
If binary calculation is used
PHP code
$ A = 765; $ t = decbin ($ A); echo bindec (str_pad (1, strlen ($ t), '0 '));
------ Solution --------------------
Discussion
PHP code
$ A = 765;
$ T = decbin ($ );
Echo bindec (str_pad (1, strlen ($ t), '0 '));