码迷,mamicode.com
首页 > 其他好文 > 详细

leecode之aoti

时间:2015-02-01 20:30:36      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:


【 声明:版权所有,欢迎转载,请勿用于商业用途。  联系信箱:feixiaoxing @163.com】


    最近一段时间,发现自己编写代码的能力下降了很多。所以,网上找了一下,看看有没有类似可以提高的项目。偶尔看别人都在leetcode上刷题目,感觉特别有意思,所以拿来练练手。因为leetcode上每个题目有很多测试用例,所以你上传的代码必须要全部通过这些测试用例才行。


    不多说,为了不丢人。先找容易的题目开始,这样也好尽快上手。atoi,其实就是字符串转变为整数的代码。看着容易,其实也不容易,因为你需要考虑各种情况,其实这对我们提高代码质量是很有帮助的。代码你可以根据自己的需要写成cpp、java或者python的格式。


    因为我的机器上没有安装vc编译器,所以只能根据网站反馈的信息进行调整,看日志前后花了快1个半小时,工作了这么多年,这个成绩还是很丢人的。大家可以根据自己的需要到leetcode上面试一试,权当练习好了。看到这份博客的同学最好先不要看代码,自己去试一试,看看能不能在保证正确的时候保证性能的最大化。


    为了不侵犯原作者的版权,这边只是给出我个人对题目的理解和答案,当然仅仅是抛砖引玉了。

#inlude <iostream>
using namespace std;

class Solution {

public:
	static int atoi(const char* str) {
	
		int index = 0;
		int neg = 0;
		int total = 0;
		int len = strlen(str);
		char val  = 0;
		int count = 0;
		if(!len) return total;
		
		while(str[index] == ‘ ‘)
			index ++;
			
		if(str[index] == ‘+‘) 
			index ++;
		else if(str[index] == ‘-‘) {
			neg = 1;
			index++;
		}
		
		for(; index < len; index ++) {
		
			val = str[index] - ‘0‘;
			
			count ++;
			if(val < 0 || val > 9)
				break;
				
			if(count > 10) {
				if(neg) total = 0x80000000;
				else total = 0x7fffffff;
				goto end;
			}
		
			if(!neg && count == 10) {
				if(val > (0x7fffffff - total * 10)) {
					total = 0x7fffffff;
					goto end;
				}
			}else if(neg && count == 10){
				if((unsigned int)val > (unsigned int)((-total * 10) - (int)(0x80000000))) {
					total = 0x80000000;
					goto end;
				}
			}
		
			total = total * 10 + val;
		}
		if (neg) total = -total;
		
	end:
		return total;
	}
};




leecode之aoti

标签:

原文地址:http://blog.csdn.net/feixiaoxing/article/details/43373627

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!