String to Integer:字符串转成整形

[ 问题: ]

Hint:Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes:It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

更多精彩内容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

[ 分析: ]① 字符串为空或空字符串, 返回0;② 忽略字符串前后空格;③ 第一个字符如果为'+'或'-'先记住它, 接着往下读, 如果读到的是数字, 则开始处理数字, 如果为其他特殊字符, 停止读取, 返回结果;④ 处理过程中, 如果转换出的值超出了int类型范围, 那么返回int的最大值或最小值.
[ 解法: ]

public class Solution {
    private final static int INT_MAX = 2147483647;
    private final static int INT_MIN = -2147483648;  

    public int atoi(String str) {
        int i = 0, flag = 1; // flag为正负标记符
        long result = 0; // 转换之后可能变成long型  

        if (str == null || str.length() == 0) {
            return 0; // step 1
        }  

        char[] ch = str.trim().toCharArray();  

        if (ch.length == 0) {
            return 0; // step 2
        }  

        if (ch[i] == '+' || ch[i] == '-') {
            flag = ch[i++] == '+' ? 1 : -1; // step 3
        }  

        while (i < ch.length && ch[i] >= '0' && ch[i] <= '9') {
            result = result * 10 + (ch[i++] - '0'); // '0'到'9' askii码为48~57
            if (result * flag < INT_MIN || result * flag > INT_MAX) {
                return result * flag < INT_MIN ? INT_MIN : INT_MAX; // step 4
            }
        }  

        return (int) result * flag;
    }  

    public static void main(String[] args) {
        System.out.println(new Solution().atoi("999"));
    }
}

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索字符串
, int
, return
, whitespace
, 字符串ip转换整形
, flag
, atoi
, returned non zero
, 字符串转整形
, The
, 字符串转int
, atoi()
Characters
string、string to int、string to json、string to date、string to byte[],以便于您获取更多的相关知识。

时间: 2024-10-05 03:20:13

String to Integer:字符串转成整形的相关文章

字符编码-vc++编码问题!把十六进制字符串转换成文字!

问题描述 vc++编码问题!把十六进制字符串转换成文字! 假设我有一个cstring a=""1A 2B"" 如何转换成文字并赋值给另外一个cstring? 解决方案 char temp[100];char src[100];strncpy(src (LPCTSTR)a 100);for (int i = 0; i < (a.GetLength() + 1)/3; i++){ temp[i] = (char)(func(src[i * 3]) * 16 + f

将JSON字符串转换成Map对象的方法_javascript技巧

页面向后台action传递一个json字符串,需要将json字符串转换成Map对象 public Map<String, String> toMap(Object object) { Map<String, String> data = new HashMap<String, String>(); // 将json字符串转换成jsonObject JSONObject jsonObject = JSONObject.fromObject(object); Iterato

请问C++中用string输入的字符串,如何转换成char[100]的字符串呢?

问题描述 请问C++中用string输入的字符串,如何转换成char[100]的字符串呢? 请问C++中用string输入的字符串,如何转换成char[100]的字符串呢? 解决方案 http://www.aichengxu.com/view/48568 解决方案二: stl 中的string,提供了c_str的方法 函数原型如下 const char* c_str() const 所以你只能得到const char *类型,结尾,但是你非要变成char[100]的类型,你自己去memcpy吧,

C#如何将string类型的二进制格式的字符串转换成二进制格式

问题描述 ffd8ffe000104a46494600010100004800480000ffe100584578696600004d4d002a000000080002011200030000000100010000876900040000000100000026000000000003a00100030000000100010000a002000400000001000008e0a003000400000001000005ec00000000ffed003850686f746f73686f7

偶数汉字转utf-8-VB将汉字字符串转换成 UTF-8格式

问题描述 VB将汉字字符串转换成 UTF-8格式 VB将汉字字符串转换成 UTF-8格式后按照JSON格式提交给服务器,偶数个汉字没有问题,但奇数个汉字时,会有问题,请大师指导. Private Declare Function MultiByteToWideChar Lib "kernel32 " (ByVal CodePage As Long, ByVal dwFlags As Long, ByVal lpMultiByteStr As Long, ByVal cchMultiBy

android字符串转换成16进制怎么转?

问题描述 android字符串转换成16进制怎么转? 求解答啊....在OnCreate中要怎么实现呢?转换之后要怎么通过密钥加密呢? 解决方案 String转换成16进制的方法:public static String str2HexStr(String str) { char[] chars = ""0123456789ABCDEF"".toCharArray(); StringBuilder sb = new StringBuilder(""

数据库-hibernate中怎么把字符串转成数字类型?

问题描述 hibernate中怎么把字符串转成数字类型? 以前用的都是mybatis,到了新的公司有项目用到了hibernate,问题是: 数据库表里的积分字段是varchar(2),对应的po类的积分字段是String类型的, 可是业务逻辑是要求按照积分来排序的,积分一般是数字,字符串的话,是不能显示正确结果的.想改表结构和po类是不行了,影响太大.怎么在查询的时候将字符串转成数字呢? 解决方案 String hql = "select CAST(字段 as integer) from 表&q

string-请问各位大侠,java字符串转化成整数为什么会出现如下的错误?谢谢

问题描述 请问各位大侠,java字符串转化成整数为什么会出现如下的错误?谢谢 type Exception report message An exception occurred processing JSP page /admin/categoryadd.jsp at line 15 description The server encountered an internal error that prevented it from fulfilling this request. exce

请问怎样把字符串转成16进制数 例如 &amp;amp;quot;0x3d000000&amp;amp;quot; 转成 0x3d000000

问题描述 请问怎样把字符串转成16进制数例如"0x3d000000"转成0x3d000000 解决方案 解决方案二:publicclassTest{//privatestaticTimert;/***@paramargs*/publicstaticvoidmain(String[]args){Strings="3d000000";//转化为16进制的intinti=Integer.parseInt(s,16);//将i输出显示为10进制System.out.prin