'Convert an int array to a single int
I'm trying to convert array[]={1,2,3} into a int number=123; how can I do that ?
my code is this:
int main()
{
int array[]={1,2,3};
int number;
for (int i =0; 3<i ; i++){
int val=1;
for(int j=0; j<i; j++ ){
val*=10;
}
number += array[i] *val;
}
cout<<number;
while(1);
return 0;
}
Solution 1:[1]
You're adding numbers in the wrong "direction". To keep the digits in order, you need to multiply your number variable by 10 and then add array[i] instead of multiplying array[i] and adding it to number.
You also need to initialize number to zero before you use it, because a variable has a random value until it's explicitly given one.
You also need to do i < 3 ("loop while i is less than three") instead of 3 < i ("loop while 3 is less than i", which is never true).
int array[] = {1,2,3};
int number = 0;
for (int i = 0; i < 3; i++) {
number *= 10;
number += array[i];
}
cout << number;
Let's walk through what happens.
- In the beginning,
numberis equal to zero. - We get to the loop. First,
iequals 0.- We multiply
numberby 10. For the first iteration,numberis still zero after that. - We add
array[0](1) tonumber.Numberis now 1.
- We multiply
inow increments and is equal to 1. 1 is less than 3, so we go in the loop body again.- We multiply
numberagain by 10 to make room for the next digit.numberis now equal to 10. - We add
array[1](2) tonumber.Numberis now 12.
- We multiply
iincrements and is equal to 2. 2 is less than 3, so we repeat.- We multiply
numberby 10, again to make room for the next digit. It's now 120. - We add
array[2](3) tonumber, making it 123, the desired result.
- We multiply
iincrements and becomes 3. 3 is obviously not less than 3, so we exit the loop.- We print
number(123) to the console.
Solution 2:[2]
I would do this using streams, as your case is really about lexical interpretation.
int number;
std::array<int, 3> arr { 1,2,3 };
std::stringstream ss;
for(int i : arr) ss << i;
ss >> number;
std::cout << number;
or course if you don't need the number itself you can just use std::cout.
std::array<int, 3> arr { 1,2,3 };
for(int i : arr) std::cout << i;
Solution 3:[3]
#include <iostream>
#include <cmath>
int main()
{
int numarray[] = {1,2,3};
int num = 0;
for(int i = 2; i>=0; i--)
{
num += numarray[2-i]*pow(10,i);
}
std::cout << num;
return 0;
}
Replace 2 with the maximum size (m) of a number array minus 1 for different sized arrays.
Solution 4:[4]
Looks like your first for loop is messed up. Try this:
for (int i =0; i<3 ; i++){
int val=1;
for(int j=0; j<(3-i); j++ ){
val*=10;
}
number += array[i] *val;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | 111111 |
| Solution 3 | HelloUni |
| Solution 4 |
