It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I need to convert two integers into two arrays of digits, so for example 544 would become arr[0] = 5, arr[1] = 4, arr[2] = 4.
I have found some algorithms doing this, but they create new array, and return this. I would have to allocate this memory for two arrays, so I wanna pass two integers by reference and do this on them directly.
I guess I can do this, because these integers are in fact template types, so they should be changeable. That's why I added C++ tag here.
Just using something like this:
int n = 544; // your number (this value will Change so you might want a copy)
int i = 0; // the array index
char a[256]; // the array
while (n) { // loop till there's nothing left
a[i++] = n % 10; // assign the last digit
n /= 10; // "right shift" the number
}
Note that this will result in returning the numbers in reverse order. This can easily be changed by modifying the initial value of i as well as the increment/decrement based on how you'd like to determine to length of the value.
(Brett Hale) I hope the poster doesn't mind, but I thought I'd add a code snippet I use for this case, since it's not easy to correctly determine the number of decimal digits prior to conversion:
{
char *df = a, *dr = a + i - 1;
int j = i >> 1;
while (j--)
{
char di = *df, dj = *dr;
*df++ = dj, *dr-- = di; /* (exchange) */
}
}
A simple solution is:
int i = 12312278;
std::vector<int> digits;
while (i)
{
digits.push_back(i % 10);
i /= 10;
}
std::reverse(digits.begin(), digits.end());
or, string based ( i >= 0 )
for (auto x : to_string(i))
digits.push_back(x-'0');
Call the integer a.
To get the units digit of a, a % 10
To shift a down so the tens is the units digit, a / 10
To know when you're done, a == 0
To know how large your array needs to be in the first place, min(ceil(log(a+1, 10)), 1) (to convince yourself this works, try the logarithm part of it in a calculator. if you don't have multiple argument log, use the identity log(x,y) == log(x)/log(y))
You can do something like this if you are using C++:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int a=544;
stringstream str;
str << a;
string arr;
str>>arr;
for(int i=0; i<arr.length(); i++)
{
cout << arr[i];
}
system("pause");
return 0;
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Is there a way to get the number of digits without the division by 10?
For example i have this:
int main()
{
int dividend = 100;
int remainder=0;
int temp = 0;
while(dividend>=10)
{
dividend = dividend-10;
temp+=1;
}
printf("Quotient: %d\n",temp);
printf("Reminder: %d\n",dividend);
}
And now I will add to calculate the number of digits of the variable dividend.
You have to know the maximum range of integer to make this function usefull.
no function call, no division ...
int nbDigitInteger(int number)
{
if (-10 < number && number < 10) return (1);
if (-100 < number && number < 100) return (2);
if (-1000 < number && number < 1000) return (3);
if (-10000 < number && number < 10000) return (4);
if (-100000 < number && number < 100000) return (5);
...
}
Sometime, the simplier is the best.
If you are allowed to use logarithms then
int i = 123456;
int digitsCount = ceil(log10(abs(i)+1.0));
cout << digitsCount;
6
Your question is too broad, and the code is also unrelated.
Since you attempted to post the code, I'll provide the guidelines for the problem you asked for. Write the code yourself.
Take the absolute integer value. (abs())
Print it to a (large enough) buffer. (sprintf()/ snprintf()).
Use strlen() to get the length of the buffer (as string).
An alternative to the very elegant solution o #Yola is this.
intPow10 is returning 10 to the power exponent. I did not use pow from math.h, since it is numerically expensive and as #Tom's pointed out it can lead to invalid results.
#include <stdio.h>
#include<math.h>
int intPow10(int exponent){
int retval=1;
while (exponent){
retval *=10;
exponent --;
}
return retval;
}
int numDigits(const int i) {
int digits = 1;
while (intPow10(digits) <= fabs(i)) {
digits++;
}
printf("%i has %i digits.\n", i,digits);
return digits;
}
int main() {
numDigits(1);
numDigits(-1);
numDigits(10);
numDigits(13);
numDigits(-112312);
}
Is this code golf or what?
int b = 1000;
char a[10] = itoa(b);
printf("%d\n", strlen(a)); // 4
This simply turns b into a string, which is a. Then, prints the length. What would we do without atoi() and itoa()? Our own functions!
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
what I'm looking for is using simple math on number in string
I'm trying to find the factorial of 100 and it's really big to put it in int or long long so I searched and found that string is the best Solution but
I can't multiply numbers in string or even put in int the multiply then put it back in string and I can't use libraries not from the std of c++ and one can help me
To solve this, you will have to write some code that multiplies a number with another number.
Here's a function that multiplies the content of a string by two:
void times_two(char *str)
{
int carry = 0;
for(int i = DIGITS-2; i >= 0; i--)
{
int t = str[i] - '0';
t *= 2;
t += carry;
str[i] = (t % 10) + '0';
carry = (t > 9);
}
}
It presumes that the string is DIGITS characters long and "adjusted" to the right of the string with zeros to fill it out.
Of course, if you try to multiply by "more than a single digit", you will have to loop over the length of the number you are multiplying by, and you also have to care about "carry" being more than one for anything over two. But the principle is the same.
[I'm intentionally not rewriting my function above to cope with those two scenarios, becuase the prupose of you doing the factorial of 100 isn't to find the answer, but to learn how to solve programming problems. If all you wanted to do is find the answer, you could just use a modern calculator!]
Here's the code I once wrote runs in O(n^2) time. There are better algorithms though like fast fourier transformatons(fft) which runs in O(nlog n) time.
The multiply functions accepts 2 strings(numbers) and returns their product.
#define itc(n) char(n+48)
#define cti(ch) (ch-48)
string itos(lld n)
{
ostringstream convert;
convert<<n;
return convert.str();
}
string add(string s1, string s2)
{
int len1=s1.length(), len2=s2.length();
if(len1<len2) //s1 should be of greater length than s2
return add(s2, s1);
string ans="";
int carry=0, i, s;
for(i=1;i<=len1;i++)
{
s = carry+cti(s1[len1-i]);
if(i<=len2)
s += cti(s2[len2-i]);
ans = itc(s%10)+ans; //finding the character to be added to the ans
carry = s/10; //finding the carry
}
if(carry!=0)
ans = itc(carry)+ans;
return ans;
}
string multiply(string s1, string s2)
{
int len1=s1.length(), len2=s2.length();
if(len1<len2)
return multiply(s2,s1);
int i,j,p, carry=0;
string result, net="", c;
for(i=len2-1;i>=0;i--)
{
carry=0;
result="";
c="";
for(j=len1-1;j>=0;j--)
{
p=cti(s1[j])*cti(s2[i]);
result = itc((p+carry)%10)+result;
carry=(p+carry)/10;
}
if(carry!=0)
{
c=itos(carry);
result=c+result;
}
for(j=i;j<len2-1;j++)
result+="0";
net=add(net,result);
}
return net;
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
What does it do - element at index 'i' is the product of all input elements except for the input element at 'i'.
As an example, if arr = { 1, 2, 3, 4 }, then
output = { 2*3*4, 1*3*4, 1*2*4, 1*2*3 }.
#include<cstdio>
#include<iostream>
using namespace std;
int main(){
int n;
long long int arr[1000]={0},prod=1;
cin>>n;
for(int i=0;i<n;i++){
cin>>arr[i];
prod*=arr[i];
}
if(prod!=0)
for(int i=0;i<n;i++){
cout<<(prod/arr[i])<<endl;
}
else
for(int i=0;i<n;i++){
cout<<"0"<<endl;
}
return 0;
}
The simplest case for which it fails is 2 0 1. The correct result would be 1 0, your result is 0 0.
More generally, it fails if there is exactly one zero and at least one non-zero in the input set.
As was already noted, the problem is when one of the inputs is zero, and you try to divide by zero. To properly compute the products, an algorithm which only performs multiplications and no divisions is needed, such as the following one.
#include <stdio.h>
#include <stddef.h>
// Input: an array of 2^(exp) doubles
// Output: an array of 2^(exp) doubles, where each one is the
// product of all the numbers at different indices in
// the input
// Return value: the product of all inputs
double products (unsigned int exp, const double *in, double *out)
{
if (exp == 0) {
out[0] = 1;
return in[0];
}
size_t half_n = (size_t)1 << (exp - 1);
double prod_left = products(exp - 1, in, out);
double prod_right = products(exp - 1, in + half_n, out + half_n);
for (size_t i = 0; i < half_n; i++) {
out[i] *= prod_right;
out[half_n + i] *= prod_left;
}
return prod_left * prod_right;
}
int main ()
{
double in[8] = {1, 2, 3, 4, 5, 6, 7, 8};
double out[8];
products(3, in, out);
for (size_t i = 0; i < 8; i++) {
printf("%f ", out[i]);
}
printf("\n");
return 0;
}
This requires O(n*log(n)) time and no extra space, except for the O(log(n)) space used by the recursion. While it's nice and easy to understand, it is not optimal; see this question.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I have compiled the following program and i know what it does, it takes ten numbers multiplies it my itself and then at the end add their total together.
#include <iostream>
using namespace std;
main()
{
int a[10];//1
int sumOfSquares = 0 ;//2
int i =0; //3`enter code here`
cout << "Please enter the ten numbers one by one " << endl;//4
for (i = 0 ; i < 10 ; i++)//5 dont get what this does,
// obviously its a for loop,
// but why does it increment i by one
{
cin >> a [i];//6 this means store the 10 numbers
// in array a and refer to it by the variable i
}
for (i = 0 ; i < 10 ; i++) //7 again i dont get why this is here
{
sumOfSquares = sumOfSquares + a[i]*a[i];//8
}
cout << "The sum of squares is "<< sumOfSquares << endl; //9
}
why does it increment i by one
Array indexes run from 0 to N-1, where N is the number of elements in the array.
i++ increments the value of i by 1 (equivalent to i = i + 1;). Incrementing i in the for loop is a construct for accessing each element of the array a (in order):
for (int i = 0; i < 10; i++)
{
a[i] = 2; /* just example */
}
is equivalent to:
a[0] = 2;
a[1] = 2;
...
a[9] = 2;
As others have commented, get a C++ book (see this SO question for a list of C++ books).
#include <iostream>
using namespace std;
main()
{
//declare space in memory for 10 numbers to be stored sequentially
//this is like having ten variables, a1, a2, a3, a4 but rather than having
//hardcoded names, you can say a[4] or rather i=4, a[i], to get variable a4.
int a[10];
int sumOfSquares = 0 ; //space for a number to be stored called sumOfSquares
int i =0; //space for a number to be stored called i
cout << "Please enter the ten numbers one by one " << endl; //print msg to screen
for (i = 0 ; i < 10 ; i++) //make i = 0; while i < 10 run this code! increase i by 1 each time
{
//a stores 10 numbers. put the number the user entered in space
//a[0] the first time, a[1] the second time, a[2] the third time etc etc.
cin >> a [i];
}
//run this code 10 times, with i=0 the first time, i=1 the second time,
// i=3 the third time etc etc.
for (i = 0 ; i < 10 ; i++)
{
//get the number at a[0] multiple it by the number at a[0]
//add it to value already in sumOfSquares so this number goes up and up and up.
//the second time through the loop get a[1] and multiply it by a[1].
sumOfSquares = sumOfSquares + a[i]*a[i];
}
//print answer to screen
cout << "The sum of squares is "<< sumOfSquares << endl; //9
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
#include <iostream>
using namespace std;
void main()
{
int i = 0;
while (i < 1000)
{
int TEMP = i * 2;
cout << i << endl;
TEMP = i;
i = i +1;
// ???
}
return;
}
I'm so confused?? :(
The Fibonacci sequence F is F(n) = F(n - 1) + F(n - 2), F(0) = 0, F(1) = 1.
Here's some psuedo-code:
Start Counter1 at 0
Start Counter2 at 1.
For i = 0 to 1000
New value = Counter1 + Counter2
Print new value
Counter2 = Counter1
Counter1 = New Value
End For
This doesn't print out 0 or 1; it starts at F(2). You can easily fix this by just printing out 0 and 1 first. Also, this code prints the first 1000 numbers. If you change this to: While Counter1 < 1000, you'll stop when you reach or pass 1000.
It's up to you to implement it, and make sure you understand how it works.
First you should check that you understand the definition of the Fibonacci numbers.
By definition, the first two Fibonacci numbers are 0 and 1, and each remaining number is the sum of the previous two. Some sources omit the initial 0, instead beginning the sequence with two 1s.
You need two variables to remember the state, not just one as you were trying to do. And you don't multiply by two, you just add the two variables.
#include <iostream>
using namespace std;
int main()
{
int i = 0;
int j = 1;
while (i < 1000)
{
/* Print a number. */
cout << i << endl;
/* Set j to the sum of i and j, and i to the old value of j. */
int TEMP = j;
j += i;
i = TEMP;
}
return 0;
}
If you would like just a hint, Google "recursion".
If you would like the answer, Google "recursion fibonacci C++", but PLEASE try to work it out with the hint above :) It's worth it.