Approach 1:
Repeated Division-modulus
operations.
long num = 123456789;
int count = 0;
while(num > 0)
{
int digit = num % 10;
if(digit == 1)
count ++;
num /= 10;
}
Approach 2:
Convert it into an String
and get the characters at the position.
long num = 123456789;
int count = 0;
String s = String.valueOf(num);
for(int i = 0; i < s.length(); i++)
{
char ch = s.charAt(i);
if(ch == '1')
count ++;
}
The second operation doesn't need to get the remainder and the quotient each time. A charAt()
method can be enough.
Which approach is considered to be better and why?
EDIT Consider taking the input from the console.
1st Case:
long num = scanner.nextLong();
2nd Case:
String s = scanner.nextLine();
Here there would be no overhead on converting the number
to string
.
Also let us assume it is for positive numbers.
In this particular case, I'd say it's reasonable to use a string representation. After all, the count you're finding is less inherently about its numeric value than its decimal string representation - you'd get a different value if you converted it into hex instead.
For operations which are more base-neutral, I'd normally avoid performing a string conversion.
Note that you don't need a StringBuffer
for your second approach. I'd use:
long num = 123456789;
int count = 0;
String text = String.valueOf(num);
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if (ch == '1') {
count++;
}
}
This is assuming performance is irrelevant, of course - which in my experience it usually is. Your first option will almost certainly be more efficient, as the second requires converting the number to a string first. But unless you need that efficiency, I'd stick with whatever code is simplest to understand - and in this case, I'd suggest that's the text-based representation.
(As an example of that: how confident are you that your first example works with negative numbers? How about the same question with your second example?)
See more on this question at Stackoverflow