zoukankan      html  css  js  c++  java
  • 字符数组转换成数字

    问题描述:

    给定一个由数字组成的字符数组,将它转换成对应的数字值。

    如:{'1','2','3','4'} ---> 1234

    4

    34 = 3*10 + 4

    234 = (2*10 + 3)*10 + 4 = 2*10*10 + 3*10 + 4

    1234 = ((1*10 + 2) * 10 + 3)* 10 + 4 = 1*10*10*10 + 2*10*10+3*10+4

    JAVA代码如下:

    public int atoi(char[] s){
            int result = 0;
            for(int i = 0; i < s.length; i++)
                result = result * 10 + s[i] - '0';
            return result;
        }

    解法二,这其实是一个递归。

    要想将“1234” ---> 1234  首先将"123"--->123,然后将 '4'--->4

    而要将"123"--->123,首先将 "12"--->12,然后将 '3'--->3

    ....

    或者可以这样理解:

    1234 = 123*10 + 4

    123 = 12*10 + 3

    12 = 1*10 + 2

    ....

    递归实现如下:

    public int strToInt(char[] c){
            return recurse(c, c.length);
        }
        
        private int recurse(char[] c, int len){//len 表示 char[] c 的长度
            if(len == 1)
                return c[len -1] - '0';
            else
                return recurse(c, len - 1) * 10 + (c[len - 1] - '0');
        }
  • 相关阅读:
    z-index
    点击按钮跳转带指定的位置
    导航-角
    弹出框
    控制叠加风格
    Python学习三
    玩转HTTP
    http-关于application/x-www-form-urlencoded等字符编码的解释说明
    Python学习二
    git merge 和 git rebase
  • 原文地址:https://www.cnblogs.com/hapjin/p/5360109.html
Copyright © 2011-2022 走看看