PAT程序设计题目——甲级1001(国际标准格式化数字)
题目原文链接是:http://www.patest.cn/contests/pat-a-practise/1001
翻译题目要求如下:
计算出两个整数的和并将结果标准化——以三位数为单位用,逗号分割,如不超过三位,则无逗号分隔。仿照国际化的数字显示标准。
输入:-1000000 9 输出:-999,991
目前想到一个办法(C++代码):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char cResult[10] = {0};
int pos = 0;
char* add(long a, long b)
{
long result = a + b;
if( result < 0 )
{
strcat( cResult, "-");
pos = 1;
}
result = abs(result); // 对负数保留符号后,就转为绝对值使用
int top = result / 1000000;
if( top > 0 )
{
sprintf( cResult + pos, "%d,", top );
pos = strlen(cResult);
}
top = result % 1000000;
top = top / 1000;
if( top > 0 || pos > 1 )
{
if ( pos > 1 ) // 存在高位,就要补0,占满位数
sprintf( cResult + pos, "%03d,", top );
else // 不存在高位,不需要补0
sprintf( cResult + pos, "%d,", top );
pos = strlen(cResult);
}
top = result % 1000;
if( top > 0 || pos > 1 )
{
if( pos > 1 ) // 高位补0同理
sprintf( cResult + pos, "%03d", top );
else
sprintf( cResult + pos, "%d", top );
pos = strlen(cResult);
}
if( pos == 0 ) //如果结果为0,需要特殊补0,否则结果为空
strcat( cResult, "0");
return cResult;
}
int main ()
{
printf("Please input 2 digits:\n");
long a, b;
scanf("%ld %ld",&a,&b);
printf("the result is :%s\n",add(a, b));
return 0;
}
Python代码实现如下:
def _main():
a,b = raw_input("please input the digit a and b\n").split(' ')
a=int(a)
b=int(b)
print("the input",a,b)
calc(a,b)
def calc(a,b):
str_result = ""
pos = 0
result = a+b
if( result < 0 ):
str_result += '-'
pos = 1
result = abs(result)
top = result / 1000000
if( top > 0 ):
str_result += str(top)
str_result += ','
pos = len(str_result)
top = result % 1000000
top = top / 1000
if( top > 0 or pos > 1 ):
str_result += str(top)
str_result += ','
pos = len(str_result)
top = result % 1000
if( top > 0 or pos > 1 ):
str_result += str(top)
pos = len(str_result)
if( pos is 0 ):
str_result += '0'
print("result:",str_result)
_main()
大家给些参考意见,谢谢!
浙公网安备 33010602011771号