经典面试编程题--atoi()函数的实现(就是模拟手算,核心代码就一句total = 10 * total + (c - '0'); 但是要注意正负号、溢出等问题)
一、功能简介
把一个字符串转换成整数
二、linux c库函数实现

/***
*long atol(char *nptr) - Convert string to long
*
*Purpose:
* Converts ASCII string pointed to by nptr to binary.
* Overflow is not detected.
*
*Entry:
* nptr = ptr to string to convert
*
*Exit:
* return long int value of the string
*
*Exceptions:
* None - overflow is not detected.
*
*******************************************************************************/ long __cdecl atol(
const char *nptr
)
{
int c; /* current char */
long total; /* current total */
int sign; /* if '-', then negative, otherwise positive */ /* skip whitespace */
while ( isspace((int)(unsigned char)*nptr) )
++nptr; c = (int)(unsigned char)*nptr++;
sign = c; /* save sign indication */
if (c == '-' || c == '+')
c = (int)(unsigned char)*nptr++; /* skip sign */ total = 0; while (isdigit(c)) {
total = 10 * total + (c - '0'); /* accumulate digit */
c = (int)(unsigned char)*nptr++; /* get next char */
} if (sign == '-')
return -total;
else
return total; /* return result, negated if necessary */
} /***
*int atoi(char *nptr) - Convert string to long
*
*Purpose:
* Converts ASCII string pointed to by nptr to binary.
* Overflow is not detected. Because of this, we can just use
* atol().
*
*Entry:
* nptr = ptr to string to convert
*
*Exit:
* return int value of the string
*
*Exceptions:
* None - overflow is not detected.
*
*******************************************************************************/ int __cdecl atoi(
const char *nptr
)
{
return (int)atol(nptr);
}

三、需要注意的问题(摘自剑指offer)
面试官至少会期待应聘都能够在不需要提示的情况下,考虑到输入的字符串中有非数字字符和正负号,要考虑到最大的正整数和最小的负整数以及溢出。同时面试试还期待应聘者能够考虑到当输入的字符串不能转换成整数时,应该如何做错误处理。
1、检查字符串是否为空
2、对非法输入,返回0,并设置全局变量
3、溢出
4、空字符串""
5、输入字符串只有"+"或"-"号
四、剑指offer实现

// StringToInt.cpp : Defines the entry point for the console application.
// // 《剑指Offer——名企面试官精讲典型编程题》代码
// 著作权所有者:何海涛 #include "stdafx.h"
#include <stdio.h>
#include <stdlib.h> long long StrToIntCore(const char* str, bool minus); enum Status {kValid = 0, kInvalid};
int g_nStatus = kValid; int StrToInt(const char* str)
{
g_nStatus = kInvalid;
long long num = 0; if(str != NULL && *str != '\0')
{
bool minus = false;
if(*str == '+')
str ++;
else if(*str == '-')
{
str ++;
minus = true;
} if(*str != '\0')
{
num = StrToIntCore(str, minus);
}
} return (int)num;
} long long StrToIntCore(const char* digit, bool minus)
{
long long num = 0; while(*digit != '\0')
{
if(*digit >= '0' && *digit <= '9')
{
int flag = minus ? -1 : 1;
num = num * 10 + flag * (*digit - '0'); if((!minus && num > 0x7FFFFFFF)
|| (minus && num < (signed int)0x80000000))
{
num = 0;
break;
} digit++;
}
else
{
num = 0;
break;
}
} if(*digit == '\0')
{
g_nStatus = kValid;
} return num;
} // ====================测试代码====================
void Test(char* string)
{
int result = StrToInt(string);
if(result == 0 && g_nStatus == kInvalid)
printf("the input %s is invalid.\n", string);
else
printf("number for %s is: %d.\n", string, result);
} int _tmain(int argc, _TCHAR* argv[])
{
Test(NULL); Test(""); Test("123"); Test("+123"); Test("-123"); Test("1a33"); Test("+0"); Test("-0"); //有效的最大正整数, 0x7FFFFFFF
Test("+2147483647"); Test("-2147483647"); Test("+2147483648"); //有效的最小负整数, 0x80000000
Test("-2147483648"); Test("+2147483649"); Test("-2147483649"); Test("+"); Test("-"); return 0;
}

五、综合库函数及剑指offer,写出如下程序(个人作品,非标准答案)

typedef enum {VALID, INVALID} ResType; //返回的结果类型
ResType g_rtRes = VALID;
bool isdigit(char ch)
{
return '0'<=ch && ch<='9';
}
int StrToInt(const char *str)
{
unsigned int iCur, iMax;
int sign;
const char *p;
//判断参数是否合法
if(!str || strlen(str)<=0){
g_rtRes = INVALID;
return 0;
}
//去掉前面空格
for(p=str; ' '==*p; p++);
//判断正负号
sign = 1;
iMax = ~(1<<8*sizeof(int)-1); //最大正整数
if('+'==*p){
p++;
}else if('-' == *p){
p++;
sign = -1;
iMax = ~iMax; // sign*iMax 就是最小负正数
}
//首位不是数字,输入非法
if(!isdigit(*p)){
g_rtRes = INVALID;
return 0;
} //首位是0,特殊处理
if('0'==*p){
if(isdigit(*(p+1))){
g_rtRes = INVALID;
}
return 0;
} //累和
for(iCur=0; isdigit(*p) && iCur<=iMax; p++){
iCur = iCur*10 + (*p - '0');
} //返回结果
if(iCur <= iMax){
return (int)(sign*iCur);
}else{
g_rtRes = INVALID;
return 0;
}
}// StrToInt

经典面试编程题--atoi()函数的实现(就是模拟手算,核心代码就一句total = 10 * total + (c - '0'); 但是要注意正负号、溢出等问题)的更多相关文章
- java经典50编程题
菲波拉契数列:有一对兔子,从出生后第 3 个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少? package com.day2; public ...
- java面试编程题
[程序1] 题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少? //这是一个菲波拉契数列问 ...
- 一道经典面试题,atoi函数的实现
参考资料 (1)atoi函数的实现 (2)<剑指offer> 题目分析 本题需要注意的有几个方面: (1)检查输入参数,指针是否为NULL: (2)去除字符串前面的空格 (3)处理正负符号 ...
- 【剑指Offer面试编程题】题目1522:包含min函数的栈--九度OJ
题目描述: 定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数. 输入: 输入可能包含多个测试样例,输入以EOF结束. 对于每个测试案例,输入的第一行为一个整数n(1<=n&l ...
- python经典面试算法题1.4:如何对链表进行重新排序
本题目摘自<Python程序员面试算法宝典>,我会每天做一道这本书上的题目,并分享出来,统一放在我博客内,收集在一个分类中. 1.4 对链表按照如下要求重新排序 [微软笔试题] 难度系数: ...
- python经典面试算法题1.2:如何从无序链表中移除重复项
本题目摘自<Python程序员面试算法宝典>,我会每天做一道这本书上的题目,并分享出来,统一放在我博客内,收集在一个分类中. 1.2 如何实现链表的逆序 [蚂蚁金服面试题] 难度系数:⭐⭐ ...
- python经典面试算法题4.1:如何找出数组中唯一的重复元素
本题目摘自<Python程序员面试算法宝典>,我会每天做一道这本书上的题目,并分享出来,统一放在我博客内,收集在一个分类中. [百度面试题] 难度系数:⭐⭐⭐ 考察频率:⭐⭐⭐⭐ 题目描述 ...
- 手写面试编程题- 数组去重 深拷贝 获取文本节点 设置奇数偶数背景色 JS中检测变量为string类型的方法 第6题闭包 将两个数组合并为一个数组 怎样添加、移除、移动、复制、创建和查找节点? 继承 对一个数组实现随机排序 让元素水平 垂直居中的三种方式 通过jQuery的extend方法实现深拷贝
第1题==>实现数组去重 通过 new Set(数组名) // var arr = [12, 12, 3, 4, 5, 4, 5, 6, 6]; // var newarr1 = new Set ...
- C++经典面试算法题
转自:http://blog.csdn.net/f_r_e_e_x/article/details/50770907 //1.实现strcpy. char* MyStrCpy( char *pDest ...
随机推荐
- ArcSDE 设置
---------------------转载----------------------- a)创建加载路径——st_shapelib.dll 执行创建库脚本:create or r ...
- hdu5389 Zero Escape
Problem Description Zero Escape, is a visual novel adventure video game directed by Kotaro Uchikoshi ...
- AE控制图层中要素可见状态的几种方法
转自原文 AE控制图层中要素可见状态的几种方法 工作中常有这样的需求,一个作业图层由几个作业员来操作,我们要 控制每一个作业员只能看到他负责的区域.作业员的可见区域控制有时候是按空间区域划分,有时候是 ...
- 【u239】整数分解
Time Limit: 1 second Memory Limit: 128 MB [问题描述] 某些数能表示成为一些互不相同的整数的阶乘之和.如9=l!+2! +3!. 现在给定一个非负整数n,要求 ...
- list数组归并去重
C#两路list数组归并去重 个相同类型已排序数据进行合并,虽然list数组中有AddRange方法,但它只是把第二个数组从第一个数组末尾插入,假如两个数组有重复数据,保存进去.还有Union方法合并 ...
- MATLAB Toolbox Path Cache is out of date and is not being used的解决
作者:朱金灿 来源:http://blog.csdn.net/clever101 使用mcc编译MATLAB\R2009a\extern\examples\compiler目录下的hello.m,编译 ...
- git与svn的不同
假设你在读这篇文章,说明你跟大多数开发人员一样对GIT感兴趣,假设你还没有机会来试一试GIT,我想如今你就要了解它了. GIT不不过个版本号控制系统,它也是个内容管理系统(CMS),工作管理系统等.假 ...
- HBase 查找版本
直接使用hbase shell命令进入shell时间会告诉版本: 进shell后.关键在version命令.能够查看版本: # hbase shell HBase Shell; enter 'help ...
- 【Python注意事项】如何理解python中间generator functions和yield表情
本篇记录自己的笔记Python的generator functions和yield理解表达式. 1. Generator Functions Python支持的generator functions语 ...
- Windows多线程系列
来自CSDN - 秒杀多线程系列.覆盖了Windows系统的线程同步机制.对于理解各种锁以及多线程典型场景很有帮助.