algorithm - Find longest alternating string of 1's and 0's -
i learning bitwise operations in assembly. in terms of bitwise operations, quite forward find longest string of 0's or 1's, how find longest string of alternating 1's , 0's.
i thought similar first 2 in sense need right shift , appropriate operation, , repeat until had 0's, couldn't figure out solution. ideas on do?
thanks!
edit
some examples: 101101010001 has string of 6 alternating 1s , 0s. number 1010 has string of 4 consecutive 1s , 0s. don't care alternating strings of 0's , 1's, 0101, 2 because of 10 in middle of it
the architecture i'm using arm a9 processor
here tried
.text .global _start _start: mov r5, #0//store final result mov r6, #0 mov r2 , #0 mov r7, #0 ldr r3 , =test_num ones: ldr r1, [r3] //load data word r1 mov r0, #0 // r0 hold result loop: cmp r1, #0 //loop until data contains no more ones beq next lsr r2, r1, #1 //perform shift, followed , xor r1, r1, r2 add r0, #1 // count number of iterations b loop next: cmp r5, r0 // movle r5, r0 b end end: b end test_num: .word 0x1fffffff, 0x7fffffff .end
this logic can use getting longest alternating bit pattern:
int last_bit = num & 1; int count = 1; int bit_at_pos; //holds lsb num = num >> 1; int longest = 1; while(num > 0){ bit_at_pos = num & 1; if(bit_at_pos == 1 - last_bit){ //checks if bit alternate last bit or not. count++; }else{ if(longest < count) longest = count; count = 1; } last_bit = bit_at_pos; num = num >> 1; } // longest answer
Comments
Post a Comment