PHP Program to XOR on Range with Explanation
PHP
Hard
PHP Operators
21 views
1 min read
82 words
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around xor, one, range. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Given L and R, print XOR of all integers in [L,R].
Input Format
One line: L R.
Output Format
One integer.
Constraints
0
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
[$L,$R]=array_map('intval',preg_split('/\\s+/', $inputText));
function xorTo($n){
$r=$n & 3;
if($r===0) return $n;
if($r===1) return 1;
if($r===2) return $n+1;
return 0;
}
echo (xorTo($R) ^ xorTo($L-1));
?>
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Given L and R, print XOR of all integers in [L,R].
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Official Solution
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
[$L,$R]=array_map('intval',preg_split('/\\s+/', $inputText));
function xorTo($n){
$r=$n & 3;
if($r===0) return $n;
if($r===1) return 1;
if($r===2) return $n+1;
return 0;
}
echo (xorTo($R) ^ xorTo($L-1));
?>
Solutions (0)
No solutions submitted yet. Be the first!