-
-
Save shaiq-dev/c8e4daca68561a95580179f42fb2aa82 to your computer and use it in GitHub Desktop.
Two Sum - Assembly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
__attribute__((naked)) | |
int* twoSum(int* nums, int numsSize, int target, int* returnSize) { | |
// Leetcode doesn't have assembly, so I will be using the | |
// inline assembly from C (following intel syntax). This is | |
// the brute force approach, O(n^2). | |
__asm__(".intel_syntax noprefix; \ | |
\ | |
/*Create a stack and load incoming parameters into it*/; \ | |
push rbx; \ | |
sub rsp, 0x40; \ | |
mov qword ptr [rsp+0x10], rdi; \ | |
mov dword ptr [rsp+0x18], esi; \ | |
mov dword ptr [rsp+0x20], edx; \ | |
mov qword ptr [rsp+0x28], rcx; \ | |
\ | |
/*malloc memory for answer*/; \ | |
mov rdi, 8; \ | |
call malloc; \ | |
mov qword ptr [rsp+0x30], rax; \ | |
\ | |
/*Outer loop*/; \ | |
xor r8, r8; \ | |
oloop%=: \ | |
mov r9, r8; \ | |
add r9, 1; \ | |
iloop%=: \ | |
mov rbx, qword ptr [rsp+0x10]; \ | |
xor rax, rax; \ | |
lea rbx, [rbx+r8*4]; \ | |
add eax, dword ptr [rbx]; \ | |
mov rbx, qword ptr [rsp+0x10]; \ | |
lea rbx, [rbx+r9*4]; \ | |
add eax, dword ptr [rbx]; \ | |
mov ebx, dword ptr [rsp+0x20]; \ | |
\ | |
/*If sum equals target, store and leave*/; \ | |
cmp ebx, eax; \ | |
jne continue%=; \ | |
mov rax, qword ptr [rsp+0x30]; \ | |
mov dword ptr [rax], r8d; \ | |
lea rax, [rax+4]; \ | |
mov dword ptr [rax], r9d; \ | |
mov rax, qword ptr [rsp+0x28]; \ | |
mov dword ptr [rax], 0x2; \ | |
jmp leave%=; \ | |
\ | |
continue%=: \ | |
inc r9; \ | |
cmp r9d, dword ptr [rsp+0x18]; \ | |
jle iloop%=; \ | |
inc r8; \ | |
cmp r8d, dword ptr [rsp+0x18]; \ | |
jle oloop%=; \ | |
\ | |
leave%=: \ | |
mov rax, qword ptr [rsp+0x30]; \ | |
add rsp, 0x40; \ | |
pop rbx; \ | |
ret; \ | |
.att_syntax; \ | |
" : :); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment