• JZ049把字符串转换成整数


    把字符串转换成整数

    题目描述

    将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0

    • 输入描述:
    • 输入一个字符串,包括数字字母符号,可以为空
    • 返回值描述:
    • 如果是合法的数值表达则返回该数字,否则返回0

    题目链接: 把字符串转换成整数

    代码

    /**
     * 标题:把字符串转换成整数
     * 题目描述
     * 将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
     * 输入描述:
     * 输入一个字符串,包括数字字母符号,可以为空
     * 返回值描述:
     * 如果是合法的数值表达则返回该数字,否则返回0
     * 题目链接:
     * https://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e?tpId=13&&tqId=11202&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
     */
    public class Jz49 {
    
        public int strToInt(String str) {
            if (str == null || str.length() == 0) {
                return 0;
            }
            boolean isNegative = str.charAt(0) == '-';
            int result = 0;
            for (int i = 0; i < str.length(); i++) {
                char c = str.charAt(i);
                if (i == 0 && (c == '+' || c == '-')) {
                    continue;
                }
                if (c < '0' || c > '9') {
                    return 0;
                }
                result = result * 10 + (c - '0');
            }
            return isNegative ? -result : result;
        }
    
        public static void main(String[] args) {
            Jz49 jz49 = new Jz49();
            System.out.println(jz49.strToInt("+32293023a"));
            System.out.println(jz49.strToInt("+2392032"));
            System.out.println(jz49.strToInt("2293043a"));
            System.out.println(jz49.strToInt("-fd3323"));
            System.out.println(jz49.strToInt("-23232942"));
            System.out.println(jz49.strToInt("292930203"));
        }
    }
    

    【每日寄语】 好的运气从清晨开始,愿你晨起有微笑,笑里有幸福。

  • 相关阅读:
    PAT 1065. A+B and C (64bit) (20)
    PAT 1042. Shuffling Machine (20)
    PAT 1001. A+B Format (20)
    HDU 2082 找单词 母函数
    NYOJ 138 找球号(二) bitset 二进制的妙用
    POJ 1151 Wormholes spfa+反向建边+负环判断+链式前向星
    POJ 1511 Invitation Cards 链式前向星+spfa+反向建边
    zzuli 2130: hipercijevi 链式前向星+BFS+输入输出外挂
    NYOJ 323 Drainage Ditches 网络流 FF 练手
    POJ 1273 Drainage Ditches 网络流 FF
  • 原文地址:https://www.cnblogs.com/kaesar/p/15776823.html
Copyright © 2020-2023  润新知