zoukankan      html  css  js  c++  java
  • 字符串面试题:将字符串转换为整数

    在上一篇博文中介绍了如何实现将整数转换为字符串,这里在介绍一个将字符串转换为整数的实现方法。

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 
     4 int isspace(int x);
     5 int isspace(int x);
     6 int my_atoi(const char *nptr);
     7 
     8 int main(void)
     9 {
    10     char str[33];
    11     int  num;
    12     scanf("%s", str);
    13     num = my_atoi(str);
    14     printf("Ans: %d
    ", num);
    15 
    16     return 0;
    17 }
    18 
    19 int isspace(int x)
    20 {
    21     if(x==' ' || x=='	' || x=='
    ' || x=='f' || x=='' || x=='
    ')
    22         return 1;
    23     else  
    24         return 0;
    25 }
    26 
    27 int isdigit(int x)
    28 {
    29     if(x<='9' && x>='0')         
    30         return 1; 
    31     else 
    32         return 0;
    33 }
    34 
    35 int my_atoi(const char *nptr)
    36 {
    37     int c;             /* current char */
    38     int total;         /* current total */
    39     int sign;          /* if '-', then negative, otherwise positive */
    40 
    41     /* skip whitespace */
    42     while ( isspace((int)(unsigned char)*nptr) )
    43         ++nptr;
    44 
    45     // 读取第一个非空白符
    46     c = (int)(unsigned char)*nptr++;
    47     sign = c;          /* save sign indication */
    48     if (c == '-' || c == '+')
    49         c = (int)(unsigned char)*nptr++;    /* skip sign */
    50 
    51     total = 0;
    52 
    53     while (isdigit(c)) {
    54         total = 10 * total + (c - '0');     /* accumulate digit */
    55         c = (int)(unsigned char)*nptr++;    /* get next char */
    56     }
    57 
    58     if (sign == '-')
    59         return -total;
    60     else
    61         return total;   /* return result, negated if necessary */
    62 }
  • 相关阅读:
    QuickSort(Java)
    MergeSort(Java)
    Silverlight中Datagrid添加Button列用于控制单行对象
    二叉搜索树(BST)demo
    svn ignore使用方法
    海量数据处理面试题及解决方法
    Android中的单元测试
    Ubuntu下配置Intellij的Android开发环境
    urlrewrite地址重写之后丢失css和js解决方案
    修改后 简单的 TCP server
  • 原文地址:https://www.cnblogs.com/xiaomanon/p/4657063.html
Copyright © 2011-2022 走看看