Reputation: 166
The program is simple. The user inputs n
and n
amount of numbers and i try to add zeros in between adjacent digits. For example if the user enters 9(n
) digits as 1 2 3 4 5 6 7 8 9 (spaced out), the program outputs 10203040506070809. The program works well for up to n=8 digits but i get funny answers from n=9 digits upwards. The range of n should be 3<=n<=15
. My program is as follows:
int main()
{
cout << "\nEnter n and n values: \n";
int n;
cin >> n;
vector<long long>nums;
int en = n;
while (en > 0)
{
long long x;
cin >> x;
nums.push_back(x);
--en;
}
int r = 2 * n - 2;
long long new_val = 0;
int j = 0;
for (int i = 0; i < n; ++i)
{
new_val = new_val + nums[i] * (pow(10, r - j));
j += 2;
}
cout << new_val << endl;
}
I don't know how to solve the issue of funny answers from n=9 to n=15.
Upvotes: 0
Views: 98
Reputation: 28
Allow me to suggest a different approach to this problem. Since containers will give you trouble holding those large numbers, then don't with them as numbers, try string instead:
After you get the numbers from the user and store them in the nums vector, do the following:
string output = "";
char temp;
for (int i = 0; i < nums.size(); i++){
temp = nums [i] + '0';
output += temp;
if (i != (nums.size()-1))
output += "0";
}
cout << output;
Using this method, the user can enter any number as large as they want. If you want the number to be from 9 to 15, you can simply add validation at the beginning without having to deal with complicated containers.
Upvotes: 0
Reputation: 595827
The main problem is long long
is only 64-bits in size, and thus can only hold up to 19 digits. Its maximum value is 9,223,372,036,854,775,807
.
It is possible to make your code work correctly up to n=10
if you simply remove pow()
(which operates on floating-point types, not integer types). For the 2nd and subsequent loop iterations, you can simply multiply new_val
by 100 before adding nums[i]
:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
cout << "\nEnter n and n values: \n";
int n;
cin >> n;
vector<long long> nums;
int en = n;
while (en > 0)
{
long long x;
cin >> x;
nums.push_back(x);
--en;
}
long long new_val = 0;
if (n > 0)
{
new_val = nums[0];
for (int i = 1; i < n; ++i)
{
new_val *= 100;
new_val += nums[i];
}
}
cout << new_val << endl;
}
However, 1020304050607080901
is 19 digits, so n>=11
will overflow past the max value of long long
.
For such high values, you need to use a BigNumber library (as most compilers do not yet have a native 128-bit numeric type). Or, just use std::string
instead of long long
:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main()
{
cout << "\nEnter n and n values: \n";
int n;
cin >> n;
vector<int> nums;
int en = n;
while (en > 0)
{
int x;
cin >> x;
nums.push_back(x);
--en;
}
ostringstream new_val;
if (n > 0)
{
new_val << nums[0];
for (int i = 1; i < n; ++i)
new_val << '0' << nums[i];
}
cout << new_val.str() << endl;
}
Upvotes: 2