Manhattan associates Interview Question
Developer Program EngineersCountry: India
Interview Type: In-Person
Seems to be correct for positive numbers. You haven't taken negatives into account, though. No one said the int's unsigned...
Won't be the fastest variant, but the easiest for me :-)
int count(int num){
char tmp[20];
snprintf(tmp, sizeof(tmp), "%d", num);
return strlen(tmp);
}
<pre lang="" line="1" title="CodeMonkey34461" class="run-this">int count(int N)
{
int lenOfN = 0;
while(N > 0)
{
lenOfN++;
N = N / 10;
}
return lenOfN;
}
</pre><pre title="CodeMonkey34461" input="yes">
</pre>
we can use string function, but it works only on integer values and positive values.. if u want to work on negative, ignore - sign before assigning to string, or float/double values ignore value after dot.
public static void main(String[] args) {
String number="200";
System.out.println("number of characters in the number is: "+number.length());
}
I will use the modulo and divide operands to store the remainder and the quotient and count the characters in a number. I am assuming the question is to find no.of characters in a number like 4328.
int count ( int num)
{
int n = 0;
int rem = num % 10;
while (rem != 0)
{
n = n + 1;
num = num / 10;
rem = num % 10;
}
return n;
}
}
- Avinash December 04, 2011