字符串转数字, 数字转字符串

to_string(x)和stoi(s)

#include <bits/stdc++.h>
using namespace std;
int main()
{	
//	string  m = "423"; 
//	cout << m << endl;
//	int res = m-'0';//这样写是不对的,会报错,跑不成 
//	cout << res;
	
	char c = '8';//c的范围只能是0-9 ,不能是两位数和两位数以上的数 
	int ans = c-'0';
	cout << ans;
//那么多位数,怎么转换为字符串?答案:   to_string(x)    //注意横杠 
	int x = 131414;
	string s = to_string(x);
	cout << "反转前" << s << endl;
	
	reverse(s.begin(),s.end());
	cout <<"反转后"<< s << endl; 
//	cout <<"反转后" << reverse(s.begin(),s.end())  << endl;
//  这样写是不对的, reverse返回不是一个字符串 
	
 
}

在这里插入图片描述

那么一个比较长的字符串, 比如12313, 456这种怎么转化为数字?有没有对应的c++函数

根据前面的分析不难写出

#include <bits/stdc++.h>
using namespace std;
int main()
{
	string s = "6782";
	int n = s.size();
	cout << n <<endl;
	int res = 0 ;
	for(int i = 0; i < n ; i ++)
	{
		res+=(s[i]-'0')*pow(10,n-i-1);
//		cout <<res << endl;
	}
	cout << res << endl;
}
	

在这里插入图片描述

#include <bits/stdc++.h>
using namespace std;
int main()
{
	string s = "6782";
	int ans = stoi(s);//字符串转数字函数 
	cout << ans << endl;
	
	cout << typeid(s).name() << endl;//注意name后有一个小括号 
	cout << typeid(ans).name()<<endl;
	double a = 123.12;
	float  b = 56.33;
	cout << typeid(a).name() << "  " << typeid(b).name() << endl;	
}
	
 

在这里插入图片描述
学到c++的stoi函数了吗? 还有判断类型的函数,同理可以有stod, stof,stoll, to后面就是数据类型,d代表double,f代表float,ll代表long long ;

练习一个题
反序数指整数各位取反之后的数。如321 的反序是123,147 的反序是741,现输入n组a,b(ab均大于0且小于10000),如果a、b反转的和等于和的反转,则输出a、b.
例如: a=123, b=456, 那么a+b的和= 123+456=579.

#include <bits/stdc++.h>
using namespace std;

int Rev(int x)
{
	string s = to_string(x);
	reverse(s.begin(),s.end());
	int res  = stoi(s); 
	return res;
}
int main()
{
	int a, b;
	cin >> a >> b;
	int res1 = Rev(a)+Rev(b);
	int res2 = a+b;
	if(Rev(res1) ==res2) cout << "YES" << endl;
	else cout << "No" << endl; 
}
	

太爱这个函数了, 自动去前面的0

在这里插入图片描述

最后一步咱们想一下暴力怎么求解,这样可以不受语言函数的限制,万一你哪一天学了java,哈哈哈

int Rev(int x)
{
	int res = 0;
	if(x < 0) {
		return 0;
	}
	while(x>0){
		res = res*10+x%10;
		x/=10;
	}
	return res;//这个函数也是能去前0 

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

海波东

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值