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

来源:互联网 发布:0基础如何自学数控编程 编辑:程序博客网 时间:2024/06/05 19:46

【思路】:本以为用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 20int 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; elsecout << 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 20int 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; elsecout << fixed << setprecision(0) << res*pow(10.0,cnt) << endl; } return 0;}



0 0