题目原文链接是:http://www.patest.cn/contests/pat-a-practise/1001
翻译题目要求如下:
计算出两个整数的和并将结果标准化——以三位数为单位用,逗号分割,如不超过三位,则无逗号分隔。仿照国际化的数字显示标准。
输入:-1000000 9 输出:-999,991
动态拾取:从低到高逐个按位获取,根据正负数追加符号,最后把数组倒置,代码实现如下(用g++编译测试通过):
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <iostream>
using namespace std;
char result[100] = {0};
long a, b;
char* add( long a, long b )
{
long num = a + b;
bool have_nagetive = false;
int length = 0;
have_nagetive = ( num >= 0 ? false : true );
num = fabs(num);
while ( num > 0 )
{
int value = num%10;
num /= 10;
if ( (length+1)%4 != 0 )
{
sprintf( result+length, "%d", value );
length++;
}
else
{
sprintf( result+length, ",%d", value );
length+=2;
}
}
if ( have_nagetive )
{
strcat( result, "-");
}
if ( length== 0 )
{
strcat( result, "0" );
}
for ( int i = 0; i < strlen(result) / 2; i++ )
{
char tmp = result[i];
result[i] = result[strlen(result) - i - 1];
result[strlen(result) - i - 1] = tmp;
}
return result;
}
int main()
{
while(cin>>a>>b){
//printf("Please input 2 digits:\n");
//scanf("%ld %ld",&a,&b);
printf("%s\n",add(a,b));
}
return 0;
}
Python 2.0 代码实现如下:
#2016.3.11 nodified
class add:
def __init__(self):
self.a = 0
self.b = 0
self.result = []
def reset(self):
self.result = []
def Add():
sum = int(add_instance.a + add_instance.b)
is_nagative = (True if(sum < 0) else False)
sum = abs(sum)
length = 0
add_instance.reset()
while( sum > 0 ):
value = sum%10
sum = sum/10
if( (length+1)%4 is 0 ):
add_instance.result.append(',')
length += 2
else:
length += 1
add_instance.result.append(value)
if( is_nagative is True ):
add_instance.result.append('-')
if(length is 0):
add_instance.result.append('0')
add_instance.result.reverse()
def _main():
while True:
try:
a,b = raw_input().split(' ')
except:
break
if( a is None or b is None ):
break
add_instance.a = int(a)
add_instance.b = int(b)
Add()
for i in range(0,add_instance.result.__len__()):
add_instance.result[i] = str(add_instance.result[i])
str_res = ('').join(add_instance.result)
print(str_res)
add_instance = add()
_main()
大家给些参考意见,谢谢!