zoukankan      html  css  js  c++  java
  • 49.字符串转int

    image

    image

    面360的时候这道题目加了一个要求就是要求小数输出整数,故增加一个关于小数点的判断

    要注意转义字符:“.”和“|”都是转义字符,必须得加"\"。同理:*和+也是如此的。
    如果用“.”作为分隔的话,必须是如下写法:
    String.split("\."),这样才能正确的分隔开,不能用String.split(".");
    如果用“|”作为分隔的话,必须是如下写法:
    String.split("\|"),这样才能正确的分隔开,不能用String.split("|");

    public class Solution49 {
        public static void main(String[] args) {
            String str = "-12345.8";
            System.out.println(StrToInt(str));
        }
        
        public static int StrToInt(String str) {
            //1.字符串为空
            if (str.trim().length()==0||str == null) {
                return 0;
            }
            //2.判断是否为负数
            int flag = 1;
            if (str.charAt(0)=='-') {
                flag = -1;
            }
            //4.如果遇到小数点
            if (str.contains(".")) {
                if (str.indexOf(".")!=str.lastIndexOf(".")) {
                    return 0 ;
                }
                String[] split = str.split("\.");
                str = split[0];
            }
            //3.开始循环遍历这个字符串
            int res = 0;
            for (int i = 0; i < str.length(); i++) {
                char everyWord = str.charAt(i);
                //符号位
                if (i==0 && (everyWord=='+'||everyWord=='-')) {
                    continue;
                }
                //非法输入
                if (everyWord<'0'||everyWord>'9') {
                    return 0;
                }
                //合法输入,取出一位,如果后面还有数字就左移(*10)
                res = res*10 + everyWord-'0';
            }
            return (res*flag);
        }
    }
  • 相关阅读:
    hdu 2112 (最短路+map)
    poj 1502 最短路+坑爹题意
    poj 1696 Space Ant (极角排序)
    poj 1410 线段相交判断
    使用本地光盘安装Microsoft .NET Framework 3.5 for Win8.1/WinServer2012R2
    Excel REPT函数使用
    tomcat7配置虚拟目录
    Tomcat 7.0的配置
    js去除空格
    JAVABEAN连接各数据库
  • 原文地址:https://www.cnblogs.com/yuange678/p/10689796.html
Copyright © 2011-2022 走看看