简体   繁体   English

在javascript中经历位操作代码中的无限循环

[英]Experiencing infinite loop in bits manipulation code in javascript

  • I am trying to solve bit manipulation question using javascript 我试图用javascript解决位操作问题
  • In the question, given an input decimal number, converting to binary number and then manipulate bits based on two conditions to produce 0 bits at all positions 在这个问题中,给定一个输入十进制数,转换为二进制数,然后根据两个条件操作位,在所有位置产生0位
  • first condition, on every i iteration LSB bit is flipped, and if bits from i+1 to end of the positions are zero, the value of bit at ith position is flipped 第一个条件,在每次迭代时LSB位被翻转,如果从i + 1到位置末尾的位为零,则第i个位置的位值被翻转
  • On every bit manipulation operation, counter value is incremented and output returning the value of counter displaying bit manipulation operations occurred for the binary number 在每个位操作操作中,计数器值递增并且输出返回计数器显示用于二进制数的位操作操作的值
  • In my code, I converted decimal to binary number and written conditions for bit manipulation operations, but the code experiences infinite loop and does not end 在我的代码中,我将十进制转换为二进制数并为位操作操作编写条件,但代码经历无限循环而不会结束
  • can you guys let me know where I made mistake and help me to solve the issue with your suggestions 你能让我知道我弄错了哪里,并帮助我解决你的建议问题
  • providing the code below: 提供以下代码:

 var decimalNumber = 77; var binaryBit = solution(decimalNumber); console.log(binaryBit); function solution (decimalNumber){ var binary=[], i=0, j=0, binary_operations=0, binary_modified=[]; while(decimalNumber > 0){ binary[i] = (decimalNumber%2); decimalNumber = Math.floor(decimalNumber/2); i++; } console.log(binary); binary = binary.reverse(); console.log(binary); while(!binary.every(zeroCheck)){ //comBinaryOperation(binary); //} //function comBinaryOperation(binary){ //for(var j=0; j<binary.length; j++){ binary[binary.length-1] = (binary[binary.length-1] == 1) ? 0 : 1; binary_modified = binary.slice(j+1, binary.length); console.log(binary_modified); if(binary_modified.every(zeroCheck)){ binary[j] = (binary[j] == 1) ? 0 : 1; } binary_operations++;j++; if(j == binary.length-1){j=0;} /*while (binary.every(zeroCheck)){ break; }*/ } //} /*if(binary.includes(1,-4) ){ binary_bit = 1; }*/ console.log(binary); return binary_operations; } function zeroCheck(element){ return element == 0; } 

Your code is going into infinite loop because this while(!binary.every(zeroCheck)) is true. 你的代码进入无限循环,因为这时while(!binary.every(zeroCheck))是真的。 Infinite loops occur mostly in while loop while(true) will go to a infinite loop. 无限循环主要出现在while循环中, while(true)将进入无限循环。
Try changing this line !binary.every(zeroCheck) to binary.every(zeroCheck) because binary.every(zeroCheck) returns a false. 尝试将此行更改为!binary.every(zeroCheck)binary.every(zeroCheck)因为binary.every(zeroCheck)返回false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM