Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
Klades
Sep 8, 2011

B-Nasty posted:

Which is where my brain went right away after being primed with FizzBuzz solutions. In pseudo code:

code:
int input = XXX;
int count =0;
for(int i = 31; i >= 0; i--){

  int powerOf2 = 2^i;

 if(input % powerOf2 == 0){
    count++;
    input -= powerOf2;
  }
}

Generally by refactoring you should not make things worse than they were when you got there. Raising to the power of i basically means you just made a nested loop. Plus, the code doesn't actually give the correct results, at least in C++. I set input to 12 and got 3, set it to 13 and got 1, set it to 2 and got 2.

If you really wanted to change the code so that someone who didn't know about bitwise operators could look at it and tell you what it was doing, it'd be something like this
code:
int count_bits (int number) {
  int bits = 0;

  while (number) {
    // Check for odd-ness
    if (number % 2) {
      ++bits;
    }

    // Shift all bits one to the right
    number >>= 1;
  }

  return bits;
}
If someone can't at least understand that maybe they aren't a good programmer.

Adbot
ADBOT LOVES YOU

Klades
Sep 8, 2011

Cuntpunch posted:

code:
private Map<string,int> Count(string input)
{
	string word = "apache";
	int length = word.length;
	Map<string, int> counts = new HashMap<string,int>();

	for(int i = 0; i < length; i ++)
	{
		if(counts[i] != null)
		{
			counts[i]++;
		}
	}

	return counts;
}
I wonder how, even supposing that worked, this would ever not return an empty map, since each letter-key would not exist at first, and therefore wouldn't be incremented.
Even better, if you've represented this accurately all it does is make a new HashMap, then increment the first six elements of that map if they exist, which they don't because it's a fresh, empty map.

  • Locked thread