Reputation: 45
I have no idea how to write a code which would take numbers from the array and equal them to an integer number without 0
.
For example, I have an array A[size]= {12,68,45,20,10}
and I need to get the answer as n= 12684521
. Any ideas or hints how to make it?
Upvotes: 0
Views: 167
Reputation: 186
It is possible to do it without using strings or stringstreams. Here's the code:
int integer(int* arr, size_t length)
{
int result = 0;
for (size_t i = 0; i < length; i++)
{
int t1 = arr[i], t2 = 0;
while (t1 != 0)
{
if(t1 % 10 != 0)
{
t2 *= 10;
t2 += t1 % 10;
}
t1 /= 10;
}
while (t2 != 0)
{
if(t2 % 10 != 0)
{
result *= 10;
result += t2 % 10;
}
t2 /= 10;
}
}
return result;
}
The quirky thing is to make two inner while loops because operations in one of those loops mirror the numbers (e.g. if arr[i]
is 68 then t2
becomes 86 and then 6 and 8 are appended to result
).
Upvotes: 1
Reputation: 143
As others mentioned you want to use a streaming object or if you are using C++20 you want to use remove_if.
You may want to check this out. You will need to know how to use streams to be a developer. What exactly does stringstream do?
Using @MikeCAT way
size_t concatArrrayNoZero(int[] a, size_t len){
std::stringstream ss;
for( auto i : a){
//add everything to buffer
ss<<i;
}
//convert the ss into a string
std::string str = ss.str();
//remove the '0' from the string then erase the extra space in the string
str.erase(std::remove(str.begin(), str.end(), '0'),
str.end());
//clear the buffer
ss.clear();
//put the nonzeros back into the buffer
ss<<str;
//make the return type
size_t r;
// get the data out of the buffer
r<<ss;
return r;
}
size_t is the max size unsigned integral type of your computer.
Also check out https://en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom for why you have erase and remove
Upvotes: 0
Reputation: 416
Here is how i would do it :
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#define size 5
int main() {
std::string ret;
//your array
int a[size]={12,68,45,20,10};
//transform to string
std::ostringstream out;
for(int i=0;i<size;i++)out << a[i];
ret = out.str();
//transform
ret.erase(remove(ret.begin(), ret.end(), '0'), ret.end());
//return string
std::cout << ret;
//return number
int ret2 = std::stoi (ret);
std::cout << ret2;
}
Console : "12684521"
Upvotes: 1