Why does my If-Else never evaluate to true? - c++

I'm supposed to count the number of times variable integer "num" divided by each of its digit results in a clean quotient (has a remainder of 0).
Note: Each digit is considered to be unique, so each occurrence of the same evenly divisible digit should be counted (i.e.: for 222, the answer is 3).
int solver(int num) //gets an integer
{
string numString = to_string(num); //convert integer to string so i can manipulate individual digits
int divisible=0; //will store a count of digits in "num" which can be divided evenly
for (int x = 1; x <= (end(numString) - begin(numString))/*string length*/; x++)
{
if (numString[x-1] == 0 || (end(numString) - begin(numString))-x >=1) //ignore digits which are 0 and or 0s that are last in the array
++x;
if (num % numString[x - 1] == 0) //THIS NEVER EVALUATES TO TRUE. HOW COME???
divisible++;
}
return divisible; //number of digits in variable "num" which can be evenly divided
}
This function ALWAYS returns 0 (that's what variable int "divisible was initialized to), because the if-else for incrementing it always evaluates to false and is skipped. I have checked and made sure the If-Else arguments hold valid numbers (they're all integers). Is it because they are all integers that the decimal part of the result never reach If-Else for evaluation? That's the best possibility I can come up with, and even then I don't know how to remedy.

learn about size() function of std::string. You don't need end and begin to get the length of a string.
numString[x-1] returns a char an ASCII code, not the digit as numeric value. The ASCII code of 0 in decimal for example is 48. To get the numeric value of a single digit you could do:
numString[x-1] - '0'

Related

Required: large number (max 1000 digits) stored in string modulo 11

I have a question, which is to find the modulo 11 of a large number. The number is stored in a string whose maximum length is 1000. I want to code it in c++. How should i go about it?
I tried doing it with long long int, but its impossible that it can handle the corner case value.
A number written in decimal positional system as a_na_{n-1}...a_0 is the number
a_n*10^n+a_{n-1}*10^{n-1}+...+a_0
Note first that this number and the number
a_0-a_{1}+a_{2}+...+(-1)^{n}a_n
which is the sum of its digits with alternating signs have the same remainder after division by 11. You can check that by subtracting both numbers and noting that the result is a multiple of 11.
Based on this, if you are given a string consisting of the decimal representation of a number, then you can compute the remainder modulo 11 like this:
int remainder11(const std::string& s) {
int result{0};
bool even{true};
for (int i = s.length() - 1; i > -1; --i) {
result += (even ? 1 : -1) * ((int)(s[i] - '0'));
even = !even;
}
return ((result % 11) + 11) % 11;
}
Ok, here is the magic (math) trick.
First imagine you have a decimal number that consists only of 1s.
Say 111111, for example. It is obvious that 111111 % 11 is 0. (Since you can always write it as the sum of a series of 11*10^n). This can be generalized to all integers consists purely of even numbers of ones. (e.g. 11, 1111, 11111111). For those with odd number of ones, just subtract one from it and you will get a 10 times some number that consists of odd numbers of one (e.g 111=1+11*10), so their modulo to 11 would be 1.
A decimal number can be always written as the form of
where a0 is the least significant digit and an is the most significant digit. Note that 10^n can be written as 10^n - 1 + 1, and 10^n - 1 is a number consists of n nines. If n is even, then you will get 9 times some even number of ones, and its modulo to 11 is always 0. If n is odd, then we get 9 times some odd number of ones, and its modulo to 11 is always 9. And don't forget we've still got a +1 after 10^n - 1 + 1 so we need to add a to the result.
We are very close to our results now: we just have to add things up and do a final modulo to 11. The pseudo-code would be like:
Initialize sum to 0.
Initialize index to 0.
For every digit d from the least to most significant:
If the index is even, sum += d
Otherwise, sum += 10 * d
++index
sum %= 11
Return sum % 11

C++: Doubling digits using recursion

This is for my "Intro to C++" course. I need to
Write a program that uses a recursive function double_all_digit that doubles all digit from an integer. For example, double_all_digits(101) will return 110011
My code below works for only one digit; I have no idea how to proceed:
int double_all_digit(int x)
{
if(x < 10)
return (x*10) + x;
}
You have the base case; now for the recursion.
split the number into the 1's digit (use modulus) and the rest.
recur on the rest; your result is that number with all the digits doubled.
multiply that result by 100; add 11 times the 1's digit.
return this value up one level.
Here's a strategy:
convert a digit to a string. (use std::to_string)
iterate over characters in the string and append 2 characters in a new string for each character in the original. (See std::string::append)
convert the resulting string to an integer.
Since it's homework, you'll have to do the coding bit. :)

How do i target a specific digit in a multiple-digit number

So I'm making a binary->decimal program where i need to target a specific digit in the number which is inputed, so for instance if the input is 100110110, how do i target the fourth digit, in this case obviously being 1, and the fifth, sixth, ... how many ever digits there are?
If the input is a binary string, store the input in a string and process it using a loop
string num = "1001010";
int l = num.length();
for(int i=0; i<l; i++) {
// num[i] is the (i+1)th bit from left;
}
how many ever digits there are?
these are called bits. To find number of bits in a variable use sizeof operator that returns number of bytes.
sizeof(variable) * 8
how do i target the fourth digit
you can test a bit with operator&:
if (8 == (variable & 8))
...
There are already detailed answers on how to do that: How do you set, clear, and toggle a single bit in C/C++?

Convert hex- bin- or decimal string to long long in C++

I have this code which handles Strings like "19485" or "10011010" or "AF294EC"...
long long toDecimalFromString(string value, Format format){
long long dec = 0;
for (int i = value.size() - 1; i >= 0; i--) {
char ch = value.at(i);
int val = int(ch);
if (ch >= '0' && ch <= '9') {
val = val - 48;
} else {
val = val - 55;
}
dec = dec + val * (long long)(pow((int) format, (value.size() - 1) - i));
}
return dec;
}
this code works for all values which are not in 2's complement.
If I pass a hex-string which is supposed to be a negativ number in decimal I don't get the right result.
If you don't handle the minus sign, it won't handle itself.
Check for it, and memorize the fact you've seen it. Then, at
the end, if you'd seen a '-' as the first character, negate
the results.
Other points:
You don't need (nor want) to use pow: it's just
results = format * results + digit each time through.
You do need to validate your input, making sure that the digit
you obtain is legal in the base (and that you don't have any
other odd characters).
You also need to check for overflow.
You should use isdigit and isalpha (or islower and
isupper) for you character checking.
You should use e.g. val -= '0' (and not 48) for your
conversion from character code to digit value.
You should use [i], and not at(i), to read the individual
characters. Compile with the usual development options, and
you'll get a crash, rather than an exception, in case of error.
But you should probably use iterators, and not an index, to go
through the string. It's far more idiomatic.
You should almost certainly accept both upper and lower case
for the alphas, and probably skip leading white space as well.
Technically, there's also no guarantee that the alphabetic
characters are in order and adjacent. In practice, I think you
can count on it for characters in the range 'A'-'F' (or
'a'-'f', but the surest way of converting character to digit
is to use table lookup.
You need to know whether the specified number is to be interpreted as signed or unsigned (in other words, is "ffffffff" -1 or 4294967295?).
If signed, then to detect a negative number test the most-significant bit. If ms bit is set, then after converting the number as you do (generating an unsigned value) take the 1's complement (bitwise negate it then add 1).
Note: to test the ms bit you can't just test the leading character. If the number is signed, is "ff" supposed to be -1 or 255?. You need to know the size of the expected result (if 32 bits and signed, then "ffffffff" is negative, or -1. But if 64 bits and signed, "ffffffff' is positive, or 4294967295). Thus there is more than one right answer for the example "ffffffff".
Instead of testing ms bit you could just test if unsigned result is greater than the "midway point" of the result range (for example 2^31 -1 for 32-bit numbers).

Number changing value when assigned to variable?

I have a little problem when assigning a result to a variable, this is happening the first time to me now. I call Convert() with "aaa" as a parameter, here is my output:
aaa
**676** *(value from cout)* = 26^(3-1)*1 **675** *(value of the variable)*
+26 = 26^(3-2)*1 700
+1 = 26^(3-3)*1 701
701
And here the code:
string alphabet="abcdefghijklmnopqrstuvwxyz";
unsigned long long Convert(string &str){
unsigned long long wvalue=0;
for(int i=0;i<str.size();++i){
size_t found=alphabet.find(str[i]);
if(found==string::npos)
cout<<"Please enter only lowercase letters of the english alphabet!"<<endl;
unsigned long long add=((found+1)*pow(26,(str.size()-(i+1))));
wvalue+=add;
if(i>0)cout<<"+";
cout<<"\t"<<((found+1)*pow(26,(str.size()-(i+1))))<<" = "<<"26^("<<str.size()<<"-"<<(i+1) <<")*"<<(found+1)<<"\t"<<wvalue<<endl;
}
return wvalue;
}
Chances are I'm missing something awfully obvious, but I cannot figure it out.
((found+1)*pow(26,(str.size()-(i+1))))
is doing the calculation, and it is doing as it is supposed to, the result within the cout-statment is correct. But the variable is substracted by 1 in the first two assignments.
pow is a floating-point function. It takes and returns floating point numbers. Assigning a floating-point number to an integer variable truncates it to an integer number, so it might have been 675.9999999 just before the assignment, which will turn into 675 when assigned to the integer variable add.
cout also rounds floating-point numbers, depending on the configuration for example to 6 significant digits. 676.0 is a better approximation than 675.999, so you see 676 in the output.
Since you don't want to calculate with real numbers but only with integral numbers, you better stay with integral functions. To take 26 to the power of n, better use multiplication n times. Since you already use a loop, and like to have the next power of 26 for every character, the best is to add a variable in which you keep the current power value, like this:
unsigned long long currentFactor = 1;
for (...) {
...
unsigned long long add = currentFactor * (found+1);
wvalue += add;
currentFactor *= 26;
}
Also note that you don't have to find the character in an alphabet string. You can also just use character arithmetic to do this:
int charNumber(char c) {
if (c >= 'a' && c <= 'z')
return c - 'a'; // calculate the position of c relative to 'a'
else
return -1; // error
}