In this post we’re going to compare human manual coding with AI generated code for the same problem.
We’re going to use the platform Codility as the vendor of the problem.
Here’s the link of the problem that we’re going to solve: https://app.codility.com/programmers/lessons/1-iterations/
1. Human generated code
// you can write to stdout for debugging purposes, e.g.
// print "this is a debug message\n";
/*
*/
function solution($number) {
$binary = (string) decbin($number);
// print "$binary\n";
$numOneCount = substr_count($binary, '1');
$numZeroCount = substr_count($binary, '0');
if ($numOneCount === 0
|| $numOneCount === 1
|| $numZeroCount === 0
) {
return 0;
}
$singleNumbers = str_split($binary);
// print_r($singleNumbers);
// print "\n";
$binaryGapsCount = [];
$binaryGapsIndex = 0;
foreach($singleNumbers as $val) {
if ($val == 1) {
$binaryGapsIndex++;
} else {
$binaryGapsCount[$binaryGapsIndex]++;
}
}
// print_r($binaryGapsCount);
unset($binaryGapsCount[0]);
// print "\n";
return max($binaryGapsCount);
}
2. AI generated code
<?php
/**
* Finds the length of the longest binary gap in a positive integer N.
*
* @param int $N Positive integer within range [1..2,147,483,647]
* @return int Length of the longest binary gap, or 0 if none exists.
*/
function solution(int $N): int
{
// Fast path: Numbers with fewer than 2 bits set to '1' cannot contain a binary gap
if ($N <= 2) {
return 0;
}
// Advance N past trailing zeroes to locate the rightmost boundary '1'
while ($N > 0 && ($N & 1) === 0) {
$N >>= 1;
}
$maxGapLength = 0;
$currentGapLength = 0;
// Process remaining bits
while ($N > 0) {
if (($N & 1) === 1) {
// Reached a boundary '1', commit the longest gap seen so far
if ($currentGapLength > $maxGapLength) {
$maxGapLength = $currentGapLength;
}
// Reset counter for the next potential gap
$currentGapLength = 0;
} else {
// Count zeros inside a gap surrounded by '1's
$currentGapLength++;
}
$N >>= 1;
}
return $maxGapLength;
}2. Comparison
1. Algorithmic Strategy & Correctness
Human Solution
- Approach: Converts the number to a binary string using
decbin(), splits it into an array of characters withstr_split(), and uses1s as group delimiters to index zero counts into an array. - Flaw / Bug (Trailing Zeroes): Unsetting
$binaryGapsCount[0]safely removes zeroes occurring before the first1. However, it fails to handle trailing zeroes properly.- Example: For $N = 160$ (
10100000in binary), the true binary gap is 1 (between the two1s). - Your code execution:
- Index 1 gets count 1 (the zero between
1and1). - Index 2 gets count 5 (the five trailing zeroes after the second
1). - The array becomes
[1 => 1, 2 => 5]. max()returns 5, which is incorrect because those five zeroes are not enclosed on the right end by a1.
- Index 1 gets count 1 (the zero between
- Example: For $N = 160$ (
Bitwise Solution
- Approach: Shifts right to drop trailing zeroes before starting the counting loop.
- Correctness: Guarantees that any zeroes counted are strictly enclosed between two
1s.
2. PHP Warnings & Notice Hazards
Human Solution
- Undefined Array Key Warning: In PHP 8+, line
$binaryGapsCount[$binaryGapsIndex]++;will throw anUndefined array keywarning/notice on the first zero encountered for any given index, because the array element hasn’t been initialized to0first. - Empty Array Warning: If all zero counts end up unclosed or pruned (e.g., $N = 32$, binary
100000),$binaryGapsCountmight end up empty or contain only unclosed gap indices. Passing an empty array tomax()throws aValueErrorin PHP 8.
Bitwise Solution
- Operates on scalar variables (
$maxGapLength,$currentGapLength) initialized to0, avoiding array allocation, uninitialized keys, or runtime PHP warnings completely.
3. Time & Space Complexity Comparison
| Metric | Bitwise Solution | String/Array Solution (Yours) |
| Time Complexity | $O(\log N)$ (~31 steps max) | $O(B)$ with ~4-5 string/array passes (decbin, substr_count $\times 2$, str_split, foreach, max) |
| Auxiliary Space | $O(1)$ | $O(B)$ (allocates string + character array + gap counts array) |
While both run fast enough for a single 32-bit integer on Codility, string and array allocations create unnecessary memory overhead compared to pure bitwise shifting.
4. Summary Table
+---------------------+-------------------+--------------------------------+
| Feature | Bitwise Solution | Provided String Solution |
+---------------------+-------------------+--------------------------------+
| Trailing Zeroes | Handled correctly | Incorrect (counts unclosed 0s) |
| PHP 8 Compatibility | Clean (No warnings)| Throws warnings (Unset key/max)|
| Memory Usage | O(1) - Constant | O(B) - Allocates multiple arrays|
| Code Clarity | Bit manipulation | Intuitive string splitting |
+---------------------+-------------------+--------------------------------+
4. Conclusion
The human solution has better readability, but the AI solution matches 100% of the score and allocates less memory.
Depending on the prompt your solution can get complex and with bad readability.
The best solution would be: (Refinement is always the best solution)
function solution(int $N): int
{
// Strip unclosed trailing and leading zeroes
$binary = trim(decbin($N), '0');
// Split by '1' to isolate gaps
$gaps = explode('1', $binary);
$max = 0;
foreach ($gaps as $gap) {
$max = max($max, strlen($gap));
}
return $max;
}
