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 a string "D", that I want to convert into the integer 4.
(Additional information from OP)
D should convert into a decimal value . I want it to be "4".
for D = "4" ; E = "5"; and so on...
It may have the combination . If AA comes ,the value should be 27 and ll increase consequetively.
It looks like this is what you want (based on your question and comments):
unsigned long long convert(string str)
{
unsigned long long result = 0;
for (int i = 0;i<str.length();i++)
result+= (str[i] - 'A' + 1) + i*26;
return result;
}
Now for "D" it will give 4, for "AA" it will give 1+26 = 27 and so on...
A one-character string isn't so hard:
const int fromBase26 = ('D' - 'A') + 1;
This will set fromBase26 to 4.
For n-digit base parsing the algorithm is something like:
set output to 0
while input digits to convert:
output *= base
output += least significant input digit
remove least significant input digit from input
Note that this reads digits from the right of the input.
char* str = "ABC";
int i, len, num, pos;
len = strlen(str);
num = 0;
pos = 1;
for (i = 0; i < len; i++) {
num += pos * ((str[i] - 'A') + 1);
pos *= 26;
}
num will contain the result.
Related
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;
}
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.
Well, I have to make a task, that will sort elements of array in UNIQUE way.
So, for example, if I input 1st string:
BOB, I have to do: 2+15+2 (because of their positioning in the alphabet) and then divide by amount of chars /3 and do that for all inputted strings and then sort them by highest to lowest. :)
My question is, how do I set value 1,2,3,4,5... for A,B,C,D,E..... (only big letters).
Thank you.
If the underlying encoding is seuqential, such as ascii.
letter - 'A' + 1
A more robust and general approach, would be to examine the char_traits of the character type.
You need to define a function
int weight(const std::string& s);
And then iterate on the string char by char and do following:
w = ch - 'A' + 1
You also may check that the char is before 'A' and 'Z' or assume that.
You need to read more about ASCII
EDIT:
Code of weight function (simplified):
int weight(const std::string& s) {
int sum = 0, i = 0;
for(i = 0; i < s.size(); i++) {
char ch = s[i];
sum += ch - 'A' + 1;
}
return sum/i;
}
If you are working on an ASCII machine, #StoryTeller's answer works. Otherwise you can create an array to map between the two:
const char letters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static const int numbers [ 256 ] = { 0 };
for ( size_t index = 0; index < sizeof letters; ++index ) {
numbers [ letters [ index ] ] = index + 1;
}
assert ( numbers [ 'A' ] == 1 )
assert ( numbers [ 'Z' ] == 26 )
To get the values you could use the following code:
int getValue(char which)
{
int ret = 0;
switch(which)
{
case 'a' : ret = 1 ; break;
case 'A' : ret = 27 ; break;
case 'b' : ret = 2 ; break;
case 'B' : ret = 28 ; break;
// and so on....
}
return ret;
}
int result = 0;
while(....)
{
result = result + getValue(myarray[counter]);
}
You only need to escape the string to array and loop through it...
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.
#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.