Click here to Skip to main content
14,700,124 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Complete the code below to create nums-array of length 500 and initialize its items having values 0 and 1 alternately starting with nums[0] = 0 (and nums[1] = 1, nums[2] = 0, etc)

int[] nums = ________________;
for (int i = 1; i < nums.length; ______)
nums[i] = _______;


This isn't for homework, just a practice question for a test. Thanks for helping in advance!!

What I have tried:

int[] nums = new int[500];
for (int i = 1; i < nums.length; i++)
nums[i] = _____;
Posted
Updated 4-Dec-19 16:28pm

1 solution

You did fill the first two properly.
For the last one, here is some hint: odd indices should have 1 as value, whereas even indices should have 0.
And performing a bitwise AND operation with 1 allows you to isolate the lowest bit:
(an even number) & 1 == 0
(an odd number) & 1 == 1

You just have to apply that logic for the remaining part.
Hope this helps.
   
Comments
chrcx 4-Dec-19 21:53pm
   
I understand the logic with odd and even numbers I just don't know the formula in which to apply it using only one line of code.
phil.o 4-Dec-19 22:09pm
   
Which variable in the code you have so far is supposed to alternate between odd and even state? (this is not a trick question, you do have a variable with this behaviour)
chrcx 4-Dec-19 22:15pm
   
i because it is counting to 500 by 1's
phil.o 4-Dec-19 22:23pm
   
Exactly. So what happens if you perform a bitwise and (&) of i with 1?
CPallini 5-Dec-19 3:01am
   
5.
phil.o 5-Dec-19 4:11am
   
Thank you Carlo.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900