关于java:JZ049把字符串转换成整数

6次阅读

共计 1111 个字符,预计需要花费 3 分钟才能阅读完成。

把字符串转换成整数

题目形容

将一个字符串转换成一个整数,要求不能应用字符串转换整数的库函数。数值为 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"));
    }
}

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

正文完
 0