如何解决C ++数组到一个数字
我不知道如何编写代码,该代码将从数组中获取数字并将其等于没有0
的整数。
例如,我有一个数组A[size]= {12,68,45,20,10}
,我需要以n= 12684521
的形式得到答案。有任何想法或提示如何实现吗?
解决方法
不使用字符串或字符串流就可以做到这一点。这是代码:
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;
}
古怪的事情是制作两个内部while循环,因为其中一个循环的操作反映了数字(例如,如果arr[i]
为68,则t2
变为86,然后将6和8附加到{ {1}}。
这是我要怎么做:
#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;
}
控制台:“ 12684521”
,正如其他人提到的那样,您要使用流对象,或者如果您正在使用C ++ 20,则要使用remove_if。
您可能想检查一下。您将需要知道如何使用流来成为开发人员。 What exactly does stringstream do?
使用@MikeCAT方式
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(),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是计算机的最大大小无符号整数类型。
还请查看https://en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom为何要删除和删除
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。