leetcode第二题

#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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值