【问题标题】:Sum of the digits from the binary representation二进制表示中的数字总和
【发布时间】:2019-07-24 03:26:24
【问题描述】:

我正在寻找一个将字符串转换为二进制并求和的 javascript 函数,我也有一个我正在寻找的示例。

假设我有一个字符串“aB1@aaaaaa”,总和应该是 27。我完全没有做这件事。请帮忙

谢谢

【问题讨论】:

  • 我真的不知道如何开始。完全卡住了
  • 这不是 SO 应该如何工作的。请至少自己开始尝试
  • 我知道,但很遗憾我不知道从哪里开始,希望你能理解。

标签: javascript jquery string binary numbers


【解决方案1】:

我不想宣扬“不费吹灰之力的问题”的行为,但这是一个足够简单的问题来回答:

const strBinSum = (str) => str
  .split('') // split the string into individual characters
  .map(s => 
    s.charCodeAt(0).toString(2) // map them to their binary representation
   )
  .join('') // join the resulting array
  .split('') // split it again
  .filter(x => x === '1') // return only 1s
  .length; // therefore summing it by returning the amount of 1s.

  strBinSum('aB1@aaaaaa'); // 27

【讨论】:

猜你喜欢
  • 2013-05-07
  • 2014-12-05
  • 2012-01-24
  • 2015-11-25
  • 2021-04-20
  • 2010-10-16
  • 2013-07-06
  • 1970-01-01
相关资源
最近更新 更多