Prerequisite – Find the element that appears once in an array where every other element appears twice
Problem – Given 11 numbers, write an assembly language program to find the element that appears once where 5 numbers appear twice and one element appears once.
Input : [01H, 02H, 09H, 01H, 01H, 02H, 0AH, 01H, 09H, 03H, 03H] Output : 0AH Every number appears even number of times, except 0AH which appears only once.
XOR of all the elements will give the number that appears once. This is because XOR of a number with itself is 0 and XOR of a number with 0 is the number itself.
^ => XOR res = 01H ^ 02H ^ 09H ^ 01H ^ 01H ^ 02H ^ 0AH ^ 01H ^ 09H ^ 03H ^ 03H Since XOR is associative and commutative : res = 0AH ^ (01H ^ 01H) ^ (01H ^ 01H) ^ (02H ^ 02H) ^ (03H ^ 03H) ^ (09H ^ 09H) = 0AH ^ 0 ^ 0 ^ 0 ^ 0 ^ 0 = 0AH ^ 0 = 0AH
- Load the address of the first number in the HL register pair
- Initialize the register C with 0BH because we have to traverse 11 elements. It acts as a counter
- Initialize the accumulator with 0
- Take XOR of the value present at the address stored in the HL register with the accumulator and increment the address in the HL register
- Repeat step 4 for the rest of the 10 elements
- Store the value of the accumulator in 201DH (arbitrary)
201DH contains the answer.
|2000H||LXI H, 2012H|
|2003H||MVI A, 00H|
|2005H||MVI C, 0BH|
|2007H||LOOP||MOV B, M|
Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.