Witam. Prosiłbym o pomoc w skonstruowaniu takiego prostego algorytmu. Działamy na tablicach. Pozornie wydaje się prosto to zrobić, jednak ciągle napotykam na jakieś błędy w swoim algorytmie. O co mi chodzi - mamy ciąg liczb np. (4,5,10,23), a w rezultacie mamy otrzymać (451023).
0
1
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
int main() {
vector<int> nums = {4, 5, 10, 23};
copy(begin(nums), end(nums), ostream_iterator<int>(cout));
return 0;
}
Wyjście się zgadza :P
2
Lecisz od początku tablicy. Dodajesz pierwszą liczbę do sumy. Mnożysz sumę przez 10dlugosc_nastepnego_czynnika. Dodajesz kolejną liczbę. itd
Więc
suma = 0
suma*=10 ->0
suma+=4 -> 4
suma*=10 -> 40
suma+=5 -> 45
suma*=100 -> 4500
suma+=10 -> 4510
suma*=100 -> 451000
suma+=23 -> 451023
voila.
0
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int tab[] = {4,5,10,23};
std::ostringstream out;
for(int a: tab)
out << a;
cout << "Suma: [" << out.str() << "]" << endl;
return 0;
}
0
Ale wy oszukujecie bo to nadal nie jest liczba :P Niemniej nic nie stoi na przeszkodzie żeby tego sklejonego stringa zapakować istringstream do inta... ;]
1
Raczej lexical_cast z boosta bo jest w większości przypadków szybszy. Można np. tak...
#include <iostream>
#include <vector>
#include <sstream>
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;
int main(void) {
vector<int> nums = {4, 5, 10, 23};
unsigned long value;
ostringstream oss;
for(const auto& value : nums) {
oss << value;
}
value = lexical_cast<unsigned long>(oss.str());
cout << value << endl;
}