将整数转换为数组

发布于 2024-08-14 05:52:13 字数 171 浏览 3 评论 0原文

我想将整数转换为数组,使其看起来如下:

int number = 123456 ;
int array[7] ;

结果:

array[0] = 1 
array[1] = 2
...
array[6] = 6

I would like to convert an integer into an array, so that it looks like the following:

int number = 123456 ;
int array[7] ;

with the result:

array[0] = 1 
array[1] = 2
...
array[6] = 6

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

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

发布评论

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

评论(13

痞味浪人 2024-08-21 05:52:13

也许更好的解决方案是逆向计算:

123456 % 10 = 6

123456 / 10 = 12345

12345 % 10 = 5

12345 / 10 = 1234

Perhaps a better solution is to work backwards:

123456 % 10 = 6

123456 / 10 = 12345

12345 % 10 = 5

12345 / 10 = 1234

绝影如岚 2024-08-21 05:52:13

只需使用模运算:

int array[6];
int number = 123456;
for (int i = 5; i >= 0; i--) {
    array[i] = number % 10;
    number /= 10;
}

just use modular arithmetic:

int array[6];
int number = 123456;
for (int i = 5; i >= 0; i--) {
    array[i] = number % 10;
    number /= 10;
}
木緿 2024-08-21 05:52:13

我想到的是,integerToArray 函数返回一个从整数值转换而来的向量。您也可以使用 main 函数来测试它:

#include <iostream>
#include <vector>
using namespace std;

vector <int> integerToArray(int x)
{
    vector <int> resultArray;
    while (true)
    {
    resultArray.insert(resultArray.begin(), x%10);
    x /= 10;
    if(x == 0)
        return resultArray;
    }
}

int main()
{
    vector <int> temp = integerToArray(1234567);
    for (auto const &element : temp)
        cout << element << " " ;
    return 0;
}

//outputs 1 2 3 4 5 6 7 

Here what I came up with, the integerToArray function returns a vector that is converted from the integer value. you can test it with the main function as well:

#include <iostream>
#include <vector>
using namespace std;

vector <int> integerToArray(int x)
{
    vector <int> resultArray;
    while (true)
    {
    resultArray.insert(resultArray.begin(), x%10);
    x /= 10;
    if(x == 0)
        return resultArray;
    }
}

int main()
{
    vector <int> temp = integerToArray(1234567);
    for (auto const &element : temp)
        cout << element << " " ;
    return 0;
}

//outputs 1 2 3 4 5 6 7 
时光与爱终年不遇 2024-08-21 05:52:13

您可以通过以下方式提取数字的最后一位:

int digit = number % 10;
number /= 10;

请注意,您还应该检查 number 是否为正数。其他值需要额外处理。

You can extract the last digit of the number this way:

int digit = number % 10;
number /= 10;

Note that you should also check whether number is positive. Other values require additional handling.

女中豪杰 2024-08-21 05:52:13

取该数字的 log10 即可得到位数。将其放入,例如 pos,然后在循环中取 10 的模 (n % 10),将结果放入数组中的位置 pos。递减 pos 并将数字除以 10。重复直到 pos == 0

如果符号为负,您想对它做什么?

Take the log10 of the number to get the number of digits. Put that in, say pos, then, in a loop, take the modulo of 10 (n % 10), put the result in the array at position pos. Decrement pos and divide the number by 10. Repeat until pos == 0

What did you want to do with the sign if it's negative?

浊酒尽余欢 2024-08-21 05:52:13
#include <cmath>
#include <vector>    

std::vector<int> vec;
for (int i = log10(input); i >= 0; i--)
{
  vec.push_back(input / int(std::pow(10, i)) % 10);
}

我认为可能是一个好方法

#include <cmath>
#include <vector>    

std::vector<int> vec;
for (int i = log10(input); i >= 0; i--)
{
  vec.push_back(input / int(std::pow(10, i)) % 10);
}

Might be a good approach, I think

陌路终见情 2024-08-21 05:52:13

我现在能想到的最简单的方法是:

char array[40];
int number = 123456;

memset(array, 0x00, sizeof(array));

sprintf(array, "%d", number);

此外,您可以将每个数字转换为 int,只需将 char 值减去 0x30 即可。

编辑:如果这是作业,你的老师可能会要求你使用 % 运算符编写程序(例如 12 % 10 = 2)。如果是这种情况,那就做好功课;-)

The easiest way I can imagine now is:

char array[40];
int number = 123456;

memset(array, 0x00, sizeof(array));

sprintf(array, "%d", number);

Additionally you can convert each digit to int just subtracting the char value by 0x30.

EDIT: If this is a homework, your teacher you probably ask you to write the program using % operator though (example 12 % 10 = 2). If this is the case, good homework ;-)

潜移默化 2024-08-21 05:52:13

您可以使用模数来确定最后一位数字。

您可以使用除法将另一个数字移动到最后一个数字的位置。

You can use modulus to determine the last digit.

And you can use division to move another digit to the last digit's place.

茶花眉 2024-08-21 05:52:13

你不能简单地“转换”它。该整数在软件中不以十进制表示。因此您想要的各个数字存在。必须对它们进行计算。

那么,给定任意数字,如何确定 1 的数量呢?

我们可以除以 10,然后取余数:对于 123,除法得到 12,余数为 3。所以我们有 3 个。 12 告诉我们过去的结果,因此它可以作为下一次迭代的输入。我们把它除以 10,得到 1,余数为 2。所以我们在十位上有 2 个,剩下 1 个可以用于百位。将其除以 10,得到 0,余数为 1。因此我们在百位得到 1,在十位得到 2,在个位得到 3。我们完成了,因为最后一个除法返回零。

You can't simply "convert" it. The integer is not represented in software in decimal notation. So the individual digits you want don't exist. They have to be computed.

So, given an arbitrary number, how can you determine the number of ones?

We could divide by ten, and then take the remainder: For 123, the division would give 12, and then there's a remainder of 3. So we have 3 ones. The 12 tells us what we have past the ones, so it can be our input for the next iteration. We take that, divide by 10, and get 1, and a remainder of 2. So we have 2 in the tens place, and 1 left to work with for the hundreds. Divide that by 10, which gives us zero, and a remainder of 1. So we get 1 in the hundreds place, 2 in the tens place, and 3 in the ones place. And we're done, as the last division returned zero.

云醉月微眠 2024-08-21 05:52:13

请参阅SO问题 语言摊牌:转换字符串数字到整数数组? 对于 C/C++ 版本(以及其他语言)。

See SO question Language showdown: Convert string of digits to array of integers? for a C/C++ version (as well as other languages).

独留℉清风醉 2024-08-21 05:52:13

如果这确实是家庭作业,那就拿给你的老师看——只是为了好玩;-)

注意!性能非常差,以笨拙的方式达到您期望的效果,通常不会在家里(工作)这样做;-)

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

typedef std::vector< int > ints_t;

struct digit2int
{
    int operator()( const char chr ) const
    {
        const int result = chr - '0';
        return result;
    }
};

void foo( const int number, ints_t* result )
{
    std::ostringstream os;
    os << number;
    const std::string& numberStr = os.str();
    std::transform(
        numberStr.begin(),
        numberStr.end(),
        std::back_inserter( *result ),
        digit2int() );
}

int main()
{
    ints_t array;
    foo( 123456, &array );
    std::copy(
        array.begin(),
        array.end(),
        std::ostream_iterator< int >( std::cout, "\n" ) );
}

if this is really homework then show it your teacher - just for fun ;-)

CAUTION! very poor performance, clumsy way to reach the effect you expect and generally don't do this at home(work) ;-)

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

typedef std::vector< int > ints_t;

struct digit2int
{
    int operator()( const char chr ) const
    {
        const int result = chr - '0';
        return result;
    }
};

void foo( const int number, ints_t* result )
{
    std::ostringstream os;
    os << number;
    const std::string& numberStr = os.str();
    std::transform(
        numberStr.begin(),
        numberStr.end(),
        std::back_inserter( *result ),
        digit2int() );
}

int main()
{
    ints_t array;
    foo( 123456, &array );
    std::copy(
        array.begin(),
        array.end(),
        std::ostream_iterator< int >( std::cout, "\n" ) );
}
守护在此方 2024-08-21 05:52:13

如果你想把它变成一个字符串,那么这真的很容易,只需按照其他人所说的使用 % 运算符即可:

假设 num = 123,我们可以这样做:

string str;
while (num > 0)
{
   str = (num % 10) + str;  //put last digit and put it into the beginning of the string
   num = num /10;  //strip out the last digit
}

现在你可以使用 str 作为字符数组。使用数组执行此操作很麻烦,因为将内容放在数组的开头需要您移动其他所有内容。我们能做的是,我们可以将每个数字放入堆栈,而不是将每个数字放入字符串中。它会将其按倒序排列,如下所示:3 2 1。然后我们可以将顶部的数字逐一弹出,并按正确的顺序将其放入数组中。你的数组将如下所示: 1 2 3。我将把实现留给你,因为这是家庭作业。

@Broam 有一个很好的解决方案,但正如他所说,这是为了向后工作。我认为OP或任何研究这个帖子的人都会希望它转发,这就是我发布这个帖子的原因。如果您有更好的解决方案,请回复,我也感兴趣。

If you wanted to turn it into a string then it would be really easy, just do what everyone else is saying about using the % operator:

Let's say num = 123, we can do this:

string str;
while (num > 0)
{
   str = (num % 10) + str;  //put last digit and put it into the beginning of the string
   num = num /10;  //strip out the last digit
}

Now you can use str as an array of chars. Doing this with an array is a hassle because putting things in the beginning of an array requires you to shift everything else. What we can do is, instead of putting each digit into a string, we can put it into a stack. It will put it in a backwards order like this: 3 2 1. Then we can pop off the top number one by one and put that into an array in the correct order. You array will look like this: 1 2 3. I will leave the implementation to you since this is homework.

@Broam has a good solution, but like he stated, it's for working backwards. I think the OP or whoever comes looking into this thread will want it forwards and that's why I'm posting this. If you have a better solution, please reply, I'm interested as well.

梦在深巷 2024-08-21 05:52:13

要将整数转换为数组,可以执行以下步骤:

  • 获取要转换为的数字的总位数
    为此,我们将使用 count_digits() 函数,该函数将在忽略前导零后返回数字总数。
digits = count_digits(n);
  • 现在我们将为结果数组动态分配内存,就像
int* arr = new int[count_digits(n)]
  • 分配内存后,我们将使用下面的 for 循环填充数组
int digits = count_digits(num);
for (int i = digits; i > 0; i--){
    arr[i-1] = num % 10;
    num = num / 10;
}

执行上述步骤后,我们将能够将整数转换为数组。请记住,num 是我们要转换为数组的数字,digits 是变量,它为我们提供给定数字中忽略前导零的位数。

To convert an integer to array, you can do the steps below:

  • Get the total number of digits in a number to which we want to convert to
    array.For this purpose, we will use count_digits() function which will return total no of digits after ignoring leading zeros.
digits = count_digits(n);
  • Now we will dynamically allocate memory for our resulting array, just like
int* arr = new int[count_digits(n)]
  • After allocating memory, we will populate the array using the for loop below
int digits = count_digits(num);
for (int i = digits; i > 0; i--){
    arr[i-1] = num % 10;
    num = num / 10;
}

After performing the steps above, we will be able to convert an integer to array. Remember, num is the number that we want to convert into array and digits is the variable which gives us the number of digits in a given number ignoring leading zeros.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文