Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to check if value exists from value?

if I have the following values

0 - a
1 - b
2 - c
4 - d
8 - e
16 - f

if i get the value 17, how would i know that values b and f are in that values, some for the others as these can be mixed together by adding, so bd value would be 6

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Convert your value to binary format. For example 17 => 10001. Then select only 1’s. You can make for loop starts from ‘a’ to ‘z’. Increase characters +1 then convert to character.

This is sample code:

function foo(num) {
  if (num == 0)
    return 'a';

  const binaryNum = (num >>> 0).toString(2);

  function nextChar(c) {
      return String.fromCharCode(c.charCodeAt(0) + 1);
  }

  var converted = '';
  var asci = 'b';
  for(var i=binaryNum.length-1; i>=0; --i) {
      if (binaryNum.charAt(i) == '1')
          converted+=asci;
      asci = nextChar(asci);
  }
  return converted;
}

console.log(foo(17));
console.log(foo(0));
console.log(foo(6));
console.log(foo(28));

Output is:

bf
a
bd
def

Note that ‘bd’ is 5.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading