如何从数字中提取每个数字?

发布于 2024-09-16 23:32:55 字数 52 浏览 4 评论 0原文

我能想到的就是重复将数字除以10(直到数字小于10)并保留计数,但是这种事情有什么技巧吗?

All I can think of is to repeatedly divide the number by 10 (until number is less than 10) and keep a count, but is there a trick for this sort of thing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

沙沙粒小 2024-09-23 23:32:55

是的,你几乎有数学方法可以做到这一点。

while (num >= 10)
    digit = num MOD 10   // and save this into an array or whatever
    num = num / 10

最后,num 将包含最后一位数字。

这是一个 Javascript 实现:

function getDigits(num) {
    var digits = [];
    while (num >= 10) {
        digits.unshift(num % 10);
        num = Math.floor(num / 10);
    }
    digits.unshift(num);
    return digits;
}

请注意,它仅适用于非负整数。

Yep, you pretty much have the mathematical way to do it right there.

while (num >= 10)
    digit = num MOD 10   // and save this into an array or whatever
    num = num / 10

at the end of this, num will contain the last digit.

Here's a Javascript implementation:

function getDigits(num) {
    var digits = [];
    while (num >= 10) {
        digits.unshift(num % 10);
        num = Math.floor(num / 10);
    }
    digits.unshift(num);
    return digits;
}

Note that it only works for non-negative integers.

起风了 2024-09-23 23:32:55

既然已经有非常可靠的方法来实现转换,为什么还要自己实现转换呢?

在伪 C 中:

char digits[10];
sprintf(digits, "%d", number);

现在你的数字字符数组(字符串)应该由数字的每个数字组成。大多数其他脚本语言也包含 sprintf 函数。

如果您想要基数 8 或基数 16 或二进制等,这将起作用。只需使用不同的格式说明符即可。

Why implement the conversion yourself when there's already a very reliable way to do it?

In pseudo-C:

char digits[10];
sprintf(digits, "%d", number);

Now your digits char array (string) should consist of each digit of the number. Most other scripting languages also contain a sprintf function.

This will work if you want base 8 or base 16 or binary, etc. Just use a different format specifier.

心奴独伤 2024-09-23 23:32:55

数学答案是除以 10 并将每个结果添加到列表中,然后反转列表的顺序。下面是执行此操作的基本 C# 算法:

List<byte> digits = new List<byte>();

while(number > 10)
{
   digits.Add(number % 10);
   number %= 10;
}
//add the last digit
digits.Add(number);

byte temp;
for(var i=0;i<digits.Count/2;i++)
{
   temp = digits[i];
   digits[i] = digits[digits.Count-(i+1)];
   digits[digits.Count-(i+1)] = temp;
}

其他“技巧”通常涉及字符串转换。下面是使用 Linq 的 C# 单行代码,它将给出与上面相同的结果:

var digits = number.ToString().Select(c=>byte.Parse(c)).ToList();

The mathematical answer is to mod by 10 and add each result to a list, then reverse the list's order. Here's a basic C# algorithm that will do this:

List<byte> digits = new List<byte>();

while(number > 10)
{
   digits.Add(number % 10);
   number %= 10;
}
//add the last digit
digits.Add(number);

byte temp;
for(var i=0;i<digits.Count/2;i++)
{
   temp = digits[i];
   digits[i] = digits[digits.Count-(i+1)];
   digits[digits.Count-(i+1)] = temp;
}

Other "tricks" usually involve a string conversion. Here's a C# one-liner using Linq that will give the same result as the above:

var digits = number.ToString().Select(c=>byte.Parse(c)).ToList();
苏璃陌 2024-09-23 23:32:55

使用您的方法的Python代码:

def digits(n):
  ds = []
  while n > 0:
    ds.append(n % 10)
    n /= 10
  ds.reverse()
  return ds

使用转换为字符串:

def digits(n):           
  return map(int, str(n))

Python code using your approach:

def digits(n):
  ds = []
  while n > 0:
    ds.append(n % 10)
    n /= 10
  ds.reverse()
  return ds

Using convertation to string:

def digits(n):           
  return map(int, str(n))
佼人 2024-09-23 23:32:55

如果它是整数,您可以将字符串表示形式转换为字符数组,然后将其转换为字节数组 (0-9)

If it is an Integer, you could convert the string representation into an array of characters, and then convert that into an array of bytes (0-9)

因为看清所以看轻 2024-09-23 23:32:55

如果您的输入数字可能很大,则更有效的算法是除以 10 的幂(例如 1000),并使用查找表:

s = ""; // or use a string builder appropriate to your language...
table = {"000", "001", ..., "999"};
tableInitial = {"unused", "1", "2", ..., "9", "10", ..., "999"};
while(n >= 1000) {
  m = n%1000;
  n /= 1000;
  s = table[m] + s;
}
s = tableInitial[n] + s;

A more efficient algorithm, if your input numbers may be large, is to divide by a power of 10, say 1000, and use a lookup table:

s = ""; // or use a string builder appropriate to your language...
table = {"000", "001", ..., "999"};
tableInitial = {"unused", "1", "2", ..., "9", "10", ..., "999"};
while(n >= 1000) {
  m = n%1000;
  n /= 1000;
  s = table[m] + s;
}
s = tableInitial[n] + s;
甜`诱少女 2024-09-23 23:32:55

不确定我是否正确理解了您想要的内容...

以下内容对您有用吗?它是用 C# 编写的...

public static List<int> ExtractDigit()
{
    // Input example
    int number = 12345;

    // Convert Integer to string   
    string numberedString = number.ToString();

    // Create a list of integers
    var numList = new List<int>();

    // Convert each character in string back to int and add to list.
    foreach (char c in numberedString)
    {
        numList.Add(Convert.ToInt32(c.ToString()));
    }

    return numList;
}

我希望对您有所帮助。

Not sure if I understood what you want correctly...

Would the below work for you?? It is written in C#...

public static List<int> ExtractDigit()
{
    // Input example
    int number = 12345;

    // Convert Integer to string   
    string numberedString = number.ToString();

    // Create a list of integers
    var numList = new List<int>();

    // Convert each character in string back to int and add to list.
    foreach (char c in numberedString)
    {
        numList.Add(Convert.ToInt32(c.ToString()));
    }

    return numList;
}

I hope i was of help.

诺曦 2024-09-23 23:32:55

给定的 python 解决方案可以使用 In fact 进一步优化

zerostr = ord('0')
def digits(n): 
    return map(lambda x: ord(x)-zerostr, str(n))

,其中 int ->; str 转换可能是完全优化的,要获取数值,最好使用数字字符串的固有字符值,该值在每种编码(包括 EBCDIC)中通过 int 给出数值 减法而不是 str 解析。

The given python solution could be further optimized using

zerostr = ord('0')
def digits(n): 
    return map(lambda x: ord(x)-zerostr, str(n))

In fact, where the int -> str conversion is probably completely optimized, to get the numeric value it's much better to use the instrinsic character value of the digit string, which in every encoding (including EBCDIC) gives the numeric value by means of an int subtraction instead of a str parsing.

半窗疏影 2024-09-23 23:32:55

以下是 JavaScript 中处理整数或字符串的可逆数组函数:

function reverse(array)
{
    var left = null;
    var right = null;
    var length = array.length;
    for (left = 0, right = length - 1; left < right; left += 1, right -= 1)
    {
        var temporary = array[left];
        array[left] = array[right];
        array[right] = temporary;
    }
    return array;
}

function toDigitsArrayFromInteger(integer, isReverse)
{
    var digits = [];

    if (integer > 0)
    {
        var floor = window.Math.floor;
        while (integer > 0)
        {
            digits.push(floor(integer % 10));
            integer = floor(integer / 10);
        }

        // Array is populated in reverse order. Un-reverse it to make it normal.
        if (!isReverse)
        {
            digits = reverse(digits);
        }
    }
    else if (integer < 0)
    {
        digits = toDigitsArrayFromInteger(-integer, isReverse);
    }
    else if (integer === 0)
    {
        digits.push(0);
    }

    return digits;
}

function toDigitsArrayFromString(string, isReverse)
{
    var digits = [];

    string += ""; // Coerce to string.

    var i = null;
    var length = string.length;
    for (i = 0; i < length; i += 1)
    {
        var integer = parseInt(string.charAt(i), 10);
        if (isFinite(integer))
        {
            digits.push(integer);
        }
    }

    if (isReverse)
    {
        digits = reverse(digits);
    }

    return digits;
}

一旦将数字作为数组,您就可以轻松地反转数组,以获得从左或从右开始的数字。

字符串函数更通用,因为它可以查找字符串中的任何数字,而整数函数仅限于整数。

基准:
http://jsperf.com/todigitsarray

两个函数之间的基准测试表明,在 Firefox 10 和 Chrome 12 中,字符串函数比整数函数快 30% 到 60%。在 Opera 12 中,整数函数稍微快了约 10%。

Here are reversible array functions in JavaScript that handle integers or strings:

function reverse(array)
{
    var left = null;
    var right = null;
    var length = array.length;
    for (left = 0, right = length - 1; left < right; left += 1, right -= 1)
    {
        var temporary = array[left];
        array[left] = array[right];
        array[right] = temporary;
    }
    return array;
}

function toDigitsArrayFromInteger(integer, isReverse)
{
    var digits = [];

    if (integer > 0)
    {
        var floor = window.Math.floor;
        while (integer > 0)
        {
            digits.push(floor(integer % 10));
            integer = floor(integer / 10);
        }

        // Array is populated in reverse order. Un-reverse it to make it normal.
        if (!isReverse)
        {
            digits = reverse(digits);
        }
    }
    else if (integer < 0)
    {
        digits = toDigitsArrayFromInteger(-integer, isReverse);
    }
    else if (integer === 0)
    {
        digits.push(0);
    }

    return digits;
}

function toDigitsArrayFromString(string, isReverse)
{
    var digits = [];

    string += ""; // Coerce to string.

    var i = null;
    var length = string.length;
    for (i = 0; i < length; i += 1)
    {
        var integer = parseInt(string.charAt(i), 10);
        if (isFinite(integer))
        {
            digits.push(integer);
        }
    }

    if (isReverse)
    {
        digits = reverse(digits);
    }

    return digits;
}

Once you have the digits as an array, you can reverse the array easily to get the digits starting from the left or from the right.

The string function is more versatile because it can find any digit in a string, whereas the integer function is limited to integers.

Benchmarks:
http://jsperf.com/todigitsarray

The benchmarks between the two functions show that in Firefox 10 and Chrome 12, the string function is 30% to 60% faster than the integer function. In Opera 12, the integer function is slightly faster by about 10%.

深陷 2024-09-23 23:32:55

下面的程序也可以工作。

public class Main {
    public static void main(String[] args) {
        int i1 =123456;
        String s =new StringBuilder(String.valueOf(i1)).toString();
        char a[]=s.toCharArray();
        for(char c : a) {
            Integer i = Integer.parseInt(c+"");
            System.out.println(i);
        }
    }
}

Following program would work as well.

public class Main {
    public static void main(String[] args) {
        int i1 =123456;
        String s =new StringBuilder(String.valueOf(i1)).toString();
        char a[]=s.toCharArray();
        for(char c : a) {
            Integer i = Integer.parseInt(c+"");
            System.out.println(i);
        }
    }
}
佼人 2024-09-23 23:32:55

JavaScript:

function digits(num) {
  return String(num).split('').map(v => +v);
}

JavaScript:

function digits(num) {
  return String(num).split('').map(v => +v);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文