zoukankan      html  css  js  c++  java
  • 字符串转换成一个整数

    题目描述

    将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。
    package solution;
    
    import java.util.Scanner;
    
    public class StrToInt {
        public static void main(String[] args) {
            System.out.println(StrToInt(""));
        }
    
        public static int StrToInt(String str) {
            if (str == null || str=="" || str.length()==0)
                return 0;
            //1.先将字符串转换成字符数组
            char[] num = str.toCharArray();
            //2.对字符数组中的每一位进行判断
            int base = 1;
            if (num[0] == '-' && num.length > 1) {
                base = -1;
            } else if (num[0] == '+' && num.length > 1) {
                base = 1;
            } else if (!((num[0] >= '0') && (num[0] <= '9'))) {
                return 0;
            }
            int sum = 0;
            int count = 0;
            for (int i = num.length - 1; i > 0; i--) {
                if(num[i] >= '0' && num[i] <= '9'){
                    sum += base * Integer.parseInt(String.valueOf(num[i])) * Math.pow(10, count);
                    count++;
                }else{
                    return 0;
                }
            }
            if(num[0] >= '0' && num[0] <= '9'){
                sum += base * Integer.parseInt(String.valueOf(num[0])) * Math.pow(10, count);
            }
            return (int)sum;
        }
    
    }
  • 相关阅读:
    树状数组简述
    八皇后
    小木棍
    智力大冲浪
    晚餐队列安排
    修理牛棚
    转圈游戏
    关押罪犯
    借教室
    跳石头
  • 原文地址:https://www.cnblogs.com/ustc-anmin/p/11396458.html
Copyright © 2011-2022 走看看