java - Given a number (bit sequence) and a bit index, how do I find the next highest order bit? -
if have input, 51 (00110011) , index representing bit index (ex. = 0 -> 1, = 2 -> 0), how find power of 2 these examples. sorry, i'm not great math notation can give sample input , output.
example: if given 51 , index 1 (00110011), want function return 00010000 = 16.
also, if given 173 , index 2 (10101101), function must return 00001000 = 8.
i'm looking solution uses bit operations , no loops based on size of number preferably.
edit: isn't homework. i'm writing program stores user selections number. i'm trying challenge myself here.
here little i've been able do
x--; (int j = 0; j < 5; j++) { x |= x >> (int) math.pow(2, i); } x++; return x;
this takes 32 bit number , returns next power of 2. i'm not sure if of use though problem. tried seeing if else had posted similar , found , thought might play in i'm trying do.
edit 2 i'm having users select days of week , store days in single number. given day, want find next day user has selected. can converting number boolean array wanted see if there other clever solutions out there. apologize if it's "homework" like.
i've realize if take number 51 (00110011) , index 1, can shave off first 2 bits dividing 2^1 = 001100. then, want program find position of first 1 (index 2). should return 2^(2+2) because shaved off 2 bits , next logical 1 @ index 2 after that.
you have use loop anyway. java, right? code:
public class test { public static void main(string[] args) { system.out.println(yourhomework(51,1)); system.out.println(yourhomework(173,2)); } public static int yourhomework(int number, int index) { // lol!! joke! (int = index + 1; < 32; i++) { if ((number | (1 << i)) == number) return 1 << i; } return 0; // or value must return if there not answer } }
does help?. test cases & works i'm not sure need.
Comments
Post a Comment