Reputation: 67
The problem I'm writing code to solve is:
A number can be broken into different contiguous sub-subsequence parts. Suppose, a number 3245 can be broken into parts like 3 2 4 5 32 24 45 324 245. And this number is a COLORFUL number, since product of every digit of a contiguous subsequence is different. Return 1 if argument int A is a colorful number and return 0 otherwise.
My code is as follows. Everything seems to be working, except I can't seem to get the correct value for int result
, or more specifically (int)array[k]
. For the number 23, I got the sum of 2 as 51, 2+3 as 101, and 3 as 51. What is happening here? I believe my syntax is correct (?).
int Solution::colorful(int A) {
int result=0;
unordered_map<int,int> map1;
string s = to_string(A);
const char array = s.c_str();
int n = s.length();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
result = 0;
for (int k = i; k <=j; k++) {
result += (int)array[k];
}
if (map1.find(result) == map1.end()) {
map1.insert({result,0});
}
else {
return 0;
}
}
}
return 1;
}
EDIT - okay I figured this was happening. I am getting the character value and not the integer value. How can I convert character 2 to the actual value of 2?
Upvotes: 0
Views: 196
Reputation: 35154
For "converting" a character value like '2'
to an integral value 2
, you'd just substract the ASCII-value of '0'
, i.e. int valOfDigit = array[k] - '0'
;
Note that atoi
or strtod
will not work in your case, since these functions require a '\0'
-terminated "string" as input, not a single character.
Further, to make sure that your input contains only digits, you could check each array[k]
, e.g. by using isdigit(array[k])
or by (array[k] >= '0' && array[k] <= '9')
.
Upvotes: 3