leetcode第二题
来源:互联网 发布:中国古代gdp数据 编辑:程序博客网 时间:2024/06/05 06:47
#include <iostream>
#include<list>
#include<string>
#include<math.h>
using namespace std;
int atoi(const char *);
int main()
{
cout<<atoi("100")<<'\n';
return 0;
}
int atoi(const char *a)
{
string s=a;
int number=s.size();
int add=0;
for(string::const_iteratori=s.begin();i<s.end();i++,number--)
{
cout<<*i-48<<endl;
add+=(*i-48)*pow(10,number-1);
}
return add;
}
问题一
//pow会出现减一的情况,原因是在Codeblocks中,在int型变量最大值的有效范围内,在2位,5位,9位,10位数时输出结果都是少1。
出现这样的现象,可能是因为pow在math.h中的函数原型是_CRTIMPdouble __cdecl pow (double, double);该函数返回的是一个double类型,在隐式转换成了int型赋值给add后直接截去了小数部分所造成的,而codeblocks和vc中结果不同,可能是因为编译器不一样截去小数部分的方法也不同。
我试了一下,要想得到正确的结果可以把add改为double型变量,至于函数的返回值类型改不改都可以。
add+=(*i-48)*pow(10,number-1);类型转换时出现截断,而不是四舍五入
在mingwmaillist找到这个问题的解答,其中有一段:“It's also likely to happen due to the old i387excess precision "feature" where all 387 computations are done with80 bits precision even if they represent 32 or 64 bit types.”
所以修改上述的add的int类型变为double类型即可规避以上问题。
问题二
//单链表反转
//strlen函数用于字符串长度的计算,对于Int\long等数组需要使用sizeof(数组名)/sizeof(元素)计算个数
#include <iostream>
#include <vector>
#include <string.h>
using namespace std;
struct Node{
int val;
struct Node *next;
Node(int x):val(x),next(NULL){}
};
int main(){
Node *head = new Node(0);
head = NULL;
int i =0;
int a[]={5,4,3,2,1};
for(;i<5;i++)
{
Node *tmp = new Node(a[i]);
tmp->next = head;
head = tmp;
}
Node *head2 = new Node(0);
head2 = head;
Node *tmp = new Node(0);
tmp=head;
while(tmp->next!=NULL){
Node *p = new Node(0);
p = tmp->next;
tmp->next = p->next;
p->next = head2;
head2 = p;
}
while(head2!=NULL){
cout<<head2->val<<endl;
head2 = head2->next;
}
return 0;
}
- 【leetcode】第二题
- leetCode OJ 第二题
- leetcode第二题
- leetcode算法第二题
- leetcode第二题AddTwoNumber
- 开始刷刷Leetcode—leetcode第二题
- Leetcode 第二题,两数链表相加
- 第二周LeetCode算法题
- leetcode第二题-----Reverse Integer
- 后缀表达式求值--leetcode第二题
- leetcode 第二题Add Two Numbers java
- Leetcode第二题_Add Two Numbers
- Leetcode第二题解题java实现
- Add Two Numbers LeetCode第二题
- leetcode第二题add two numbers
- leetcode第二题Add Two Numbers
- Leetcode动态规划题答案第二期
- 每天一题LeetCode [第二天]
- 【bzoj1611】【Usaco2008 Feb】Meteor Shower流星雨 (bfs)题解&代码
- http协议
- ZOJ 2112 Dynamic Rankings(线段树套treap求动态第K大)
- Appium使用教程_Android篇
- Oracle 导出导入数据
- leetcode第二题
- 嵌入式Linux中几种image的区别
- Android实用代码七段(三)
- 垂直progressbar 实现
- makefile中的patsubst
- C/C++ 数据结构---线性顺序存储数据:查询快,增删慢
- 解决在onCreate()过程中获取View的width和Height为0的4种方法
- 求两个自然数的最大公约数(GCD)?
- 常用1