程序需求:palindrome(回文)是指正读和反读都一样的数或文本。例如:11、121、12321等,编写程序,求0到10000之间所有回文数并输出。要求每行输出10个数。
编程思路:汇编中esi相当于C语言中的i变量,eax相当于tmp变量,ecx相当于result变量,count用来统计回文数的个数。
开发环境
Win10 + VS2017
C语言代码实现如下:
#include <stdio.h>
int main()
{
int count = 0;
for (int i = 0; i < 10000; i++)
{
int tmp = i;
int result = 0;
while (tmp != 0)
{
result = result * 10 + tmp % 10;
tmp = tmp / 10;
}
if (result == i)
{
printf("%d\t", result);
count++;
if (count % 10 == 0)
printf("\n");
}
}
return 0;
}
汇编语言代码实现如下:
INCLUDELIB kernel32.lib
INCLUDELIB ucrt.lib
INCLUDELIB legacy_stdio_definitions.lib
.386
.model flat,stdcall
ExitProcess PROTO,
dwExitCode:DWORD
printf PROTO C : dword,:vararg
scanf PROTO C : dword,:vararg
.data
count dword 0
msg1 byte '%d',9,0
msg2 byte 10,0
.code
main Proc
mov esi,0;esi == i
jmp testing
body:
mov eax,esi;eax == tmp
mov ecx,0;ecx == result
jmp testing2
body2:
mov ebx,10
cdq
div ebx
imul ecx,10
add ecx,edx
testing2:
cmp eax,0
jne body2
cmp ecx,esi
jne over
pushad
invoke printf,offset msg1,ecx
popad
mov ebx,dword ptr count
inc ebx
mov dword ptr count,ebx
mov eax,ebx
mov ebx,10
cdq
div ebx
cmp edx,0
jne over
pushad
invoke printf,offset msg2
popad
over:
inc esi
testing:
cmp esi,10000
jl body
push 0h
call ExitProcess
main endp
end main