HDOJ 1266 Reverse Number(字符串数字转换)

本文介绍了一种使用C++实现字符串反转的方法,并解决了在处理大整数时遇到的精度问题。通过itoa和atoll函数进行整数与字符串的相互转换,利用pow函数处理大数乘方运算,同时介绍了如何避免科学计数法输出。

【思路】:本以为用atoi和itoa两种函数就可以完成,结果悲剧了。如下:

1. 输入时int范围的,但是转换后可能不是int范围内,所以要用long long,注意(long 和 int 范围相同)。所以试着谢了下atoll函数,结果居然可用!!!可是居然在OJ上不识别!

2. 换了方法,但是在这个方法中知道  cout << fixed << setprecision(0) <<  取消科学计数法。

【代码】:

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iomanip>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

#define MAX 20

int main(int argc, char** argv) {
	
	int T = 0;
	cin >> T;
	while (T--)
	{
		int n = 0, cnt = 0, i = 0, flag = 0;
		char num[MAX];
		cin >> n;
		if (n <0)
			flag = 1;
		itoa(abs(n), num, 10);
		
		for (cnt = 0, i = strlen(num)-1; num[i] == '0'; i--, cnt++);
		
		for (i = 0; i < strlen(num)/2; i++)
		{
			char temp;
			temp = num[i];
			num[i] = num[strlen(num)-1-i];
			num[strlen(num)-1-i] = temp;
		}
		
		if (1 == flag)
			cout << fixed << setprecision(0) << atoll(num)*pow(10, cnt)*-1 << endl; 
		else
			cout << fixed << setprecision(0) << atoll(num)*pow(10, cnt) << endl; 
	} 
	return 0;
}

【AC代码】:

【注意】:

1、涉及到一个精度的问题,可以再结果上加上0.01转换成int。

2、在pow里注意第一个参数是double,第二个参数是double或者int。strlen()是uint,在OJ上报错!

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iomanip>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

#define MAX 20

int main(int argc, char** argv) {
	
	int T = 0;
	cin >> T;
	while (T--)
	{
		int n = 0, cnt = 0, i = 0, flag = 0;
		char num[MAX];
		cin >> n;
		if (n <0)
			flag = 1;
		itoa(abs(n), num, 10);
		
		for (cnt = 0, i = strlen(num)-1; num[i] == '0'; i--, cnt++);
		
		for (i = 0; i < strlen(num)/2; i++)
		{
			char temp;
			temp = num[i];
			num[i] = num[strlen(num)-1-i];
			num[strlen(num)-1-i] = temp;
		}
		
		long long res = 0;
 		for (i = strlen(num)-1; i >=0; i--)
		{ 
			long long  mul = pow(10.0, (int)(strlen(num)-1)-i)+0.01;
			long long  temp =  (num[i]-'0')*mul;
			res += temp; 
		} 
		
		if (1 == flag)
			cout << fixed << setprecision(0) << res*-1*pow(10.0,cnt) << endl; 
		else
			cout << fixed << setprecision(0) << res*pow(10.0,cnt) << endl; 
	} 
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值