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
出现这样的现象,可能是因为powmath.h中的函数原型是_CRTIMPdouble __cdecl pow (double, double);该函数返回的是一个double类型,在隐式转换成了int型赋值给add后直接截去了小数部分所造成的,而codeblocksvc中结果不同,可能是因为编译器不一样截去小数部分的方法也不同。
我试了一下,要想得到正确的结果可以把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.”

 

所以修改上述的addint类型变为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;


}

0 0
原创粉丝点击