Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialClaire Gersabeck
2,368 PointsNot sure why my answer for this powers challenge is not correct
Here is the task: Create a static method named GetPowersOf2 that returns a list of integers of type List<int> containing the powers of 2 from 0 to the value passed in. For example, if 4 is passed in, the method should return this list of integers: { 1, 2, 4, 8, 16 }. The System.Math.Pow method will come in handy.
using System.Collections.Generic;
namespace Treehouse.CodeChallenges
{
public static class MathHelpers
{
public static List<int> GetPowersOf2(int value){
List<int> ints = new List<int>(value + 1);
for (int i=0; i<ints.Count; i++){
ints[i]=(int)System.Math.Pow(2, i);
}
return ints;
}
}
}
1 Answer
zalkortis
10,332 PointsThe issue is with two things:
1) You initialize ints with (value +1) and then use ints.Count in the for-header. The issue here is, that ints.Count returns 0 as long as there are no values within the List.
2) You don't add items to a list with ints[i], thats for Arrays. For Lists you should use ints.Add().
So the corrections for your code looks like this:
List<int> ints = new List<int>();
for (int i=0; i < value +1; i++)
ints.Add((int)System.Math.Pow(2, i));