[TOC]
### 1、 字符數字二進制
>[warning] Write a function that takes an (unsigned) integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
**Example:**
>>[warning] The binary representation of 1234 is 10011010010, so the function should return 5 in this case.
第一個算是常規解法了,也是我的解法~~
```js
var countBits = function(n) {
let result = 0;
n.toString(2).split('').filter(item=>{
if(item == 1){
return result+=1;
}
});
return result
};
```
<div class="cline"></div>
摘錄幾個牛逼的方法
```js
function countBits(n) {
for(c=0;n;n>>=1)c+=n&1
return c;
}
```
```js
countBits = n => n.toString(2).split('0').join('').length;
```
```js
var countBits = function(n)
{
a = n.toString(2).match(/1/g);
return a == null ? 0 : a.length;
};
```
### 2、 獲取字符串數組最長字段
>[warning] 2. 截取字符串數組中最長的字符串,blalala
```js
function longestConsec(strarr, k) {
let n = strarr.length,result="";
if(n === 0 || k>n || k<=0){
return "";
}
strarr.sort(function(a,b){
return a.length<b.length;
});
for(let i =0;i<k;i++){
result+=strarr[i];
}
return result;
}
longestConsec(["wlwsasphmxx","owiaxujylentrklctozmymu","wpgozvxxiu"], 2)
```
### 3、字符串字母序號
>[warning] In this kata you are required to, given a string, replace every letter with its position in the alphabet.
If anything in the text isn't a letter, ignore it and don't return it.
a being 1, b being 2, etc.
**As an example:**
```
alphabet_position("The sunset sets at twelve o' clock.")
```
>[warning] Should return `"20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11"` as a string.
<div class="cline"></div>
```js
function alphabetPosition(text) {
const target = 'abcdefghijklmnopqrstuvwxyz'.split('');
let array = text.toLowerCase().match(/[a-z]/g);
if(null == array)return '';
text = array.map(item=>{
return target.indexOf(item)+1;
}).join(' ');
return text;
}
```
<div class="cline"></div>
```js
function alphabetPosition(text) {
var result = "";
for (var i = 0; i < text.length; i++){
var code = text.toUpperCase().charCodeAt(i)
if (code > 64 && code < 91) result += (code - 64) + " ";
}
return result.slice(0, result.length-1);
}
```
<div class="cline"></div>
```js
let alphabetPosition = (text) => text.toUpperCase().replace(/[^A-Z]/g, '').split('').map(ch => ch.charCodeAt(0) - 64).join(' ');
```
<a class="crun" href="http://jsbin.com/duqehal/edit?html,js,console" target="_blank"></a>
### 4、求數組中出現奇數次的值
>[warning] Given an array, find the int that appears an odd number of times.
There will always be only one integer that appears an odd number of times.
```js
//搓方法
function findOdd(param) {
let set = new Set(param),
result = '';
[...set].forEach(item=>{
let count = 0;
param.forEach(p=>{
if(item == p){
count++
}
});
if(count%2 !== 0){
result = item
}
});
return result;
}
```
```js
const findOdd = (xs)=>{
return xs.reduce((a,b)=>{
return a^b
});
}
console.log(findOdd([20,5,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]));
```
<div class="cline"></div>
```js
//對象屬性去重,計數法
function findOdd(A) {
var obj = {};
A.forEach(function(el){
obj[el] ? obj[el]++ : obj[el] = 1;
});
for(prop in obj) {
if(obj[prop] % 2 !== 0) return Number(prop);
}
}
//更好的實踐,只有一循環
function findOdd(A) {
var trace = {};
A.forEach(function(x) {
if (trace[x]) delete trace[x];
else trace[x] = true;
});
return parseInt(Object.keys(trace)[0]);
}
```
<a class="crun" href="http://jsbin.com/xikoji/edit?js,console" target="_blank"></a>
關于方法二的解釋,下面引用下:
After having my mind blown by this solution and spending the next hour trying to really understand why this worked, I'd like to try to explain it:
`^ is the XOR Bitwise Operator`
From Wikipedia: https://en.wikipedia.org/wiki/Bitwise_operation#XOR
A bitwise XOR takes two bit patterns of equal length and performs the logical exclusive OR operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. In this we perform the comparison of two bits, being 1 if the two bits are different, and 0 if they are the same.
`16 ^ 6 -> 22`
Looks like this when broken down into binary:
```
/# [32] [16] [8] [4] [2] [1]
16 0 1 0 0 0 0
6 0 0 0 1 1 0
22 0 1 0 1 1 0
```
If the column values are the same (ie: 1/1 or 0/0) then the result for that column is 0
If the column values are different (as in columns [16], [4], and [2]) then the result for that column is 1.
Because of this, "same" = 0 & "different" = 1, rule, if the same # occurs twice, it becomes cancelled out of the result.
`22 ^ 22 -> 0`
```
/# [32] [16] [8] [4] [2] [1]
22 0 1 0 1 1 0
22 0 1 0 1 1 0
0 0 0 0 0 0 0
```
So for this Kata, only the # that shows up an ODD number of times will survive 'til the end.
```
/# [32] [16] [8] [4] [2] [1]
5 0 0 0 1 0 1 - ODD
5 0 0 0 1 0 1 - EVEN
0 0 0 0 0 0 0 - ^ result
5 0 0 0 1 0 1 - ODD
```
Hope that helps!
### 5、過濾非數字數組
>[warning] In this kata you will create a function that takes a list of non-negative integers and strings and returns a new list with the strings filtered out.
**Example**
```js
filter_list([1,2,'a','b']) == [1,2]
filter_list([1,'a','b',0,15]) == [1,0,15]
filter_list([1,2,'aasf','1','123',123]) == [1,2,123]
```
解答:
```js
function filter_list(l) {
return l.filter(item=>typeof item =='number')
}
```
### 6、字符串格式化
>[warning] Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number.
>**Example:**
>
```js
createPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) // => returns "(123) 456-7890"
```
>>[warning] The returned format must be correct in order to complete this challenge.
Don't forget the space after the closing parenthesis!
我的解法:
```js
//該方法計算替換的下標不夠直觀
function createPhoneNumber(numbers){
numbers.unshift('(');
numbers.splice(4,0,')',' ')
numbers.splice(9,0,'-')
return numbers.join('');
}
```
別人家的代碼
```js
//這個方法算是比較巧妙吧
function createPhoneNumber(numbers){
let format = '(xxx) xxx-xxxx';
for(var i = 0; i < numbers.length; i++)
{
format = format.replace('x', numbers[i]);
}
return format;
}
```
<div class="cline"></div>
```js
//這個方法跟我的差不多,一個是操作數組,一個操作字符串,可能效率相對會高點
function createPhoneNumber(numbers){
numbers = numbers.join('');
return '(' + numbers.substring(0, 3) + ') '
+ numbers.substring(3, 6)
+ '-'
+ numbers.substring(6);
}
```
<div class="cline"></div>
```js
//這個就牛逼了
function createPhoneNumber(numbers){
return numbers.join('').replace(/(...)(...)(.*)/, '($1) $2-$3');
}
```
先看下[官方文檔](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter)的描述:

| 字符 | 替換文本 |
| --- | --- |
| $1、$2、...、$99 | 與 regexp 中的第 1 到第 99 個子表達式相匹配的文本。 |
| $& | 與 regexp 相匹配的子串。 |
| $\` | 位于匹配子串左側的文本。 |
| $' | 位于匹配子串右側的文本。 |
| $$ | 直接量符號。 |
>[success] 字符串 stringObject 的 replace() 方法執行的是查找并替換的操作。它將在 stringObject 中查找與 regexp 相匹配的子字符串,然后用 replacement 來替換這些子串。如果 regexp 具有全局標志 g,那么 replace() 方法將替換所有匹配的子串。否則,它只替換第一個匹配子串。
replacement 可以是字符串,也可以是函數。如果它是字符串,那么每個匹配都將由字符串替換。但是 replacement 中的 $ 字符具有特定的含義。如下表所示,它說明從模式匹配得到的字符串將用于替換。
### 7、數字按位和的組合
>[warning] Write Number in Expanded Form
You will be given a number and you will need to return it as a string in Expanded Form.
**For Example:**
```js
expandedForm(12); // Should return '10 + 2'
expandedForm(42); // Should return '40 + 2'
expandedForm(70304); // Should return '70000 + 300 + 4'
```
>[warning] NOTE: All numbers will be whole numbers greater than 0.
我的解法:
```js
function expandedForm(num) {
num=num.toString();
let len = num.length;
let result = num.split('').map((item,index)=>{
return Number(item) * Math.pow(10,len-index-1)
});
return result.filter(item=>item!=0).join(' + ')
}
```
這次其他人的解法也差不多,大同小異,主要還是需要一次`map`拿到數組新的映射,再一次`filter`過濾掉值為0的項,下面摘錄一個簡單的寫法(代碼可讀性并不見得好):
```js
const expandedForm = n => n.toString()
.split("")
.reverse()
.map( (a, i) => a * Math.pow(10, i))
.filter(a => a > 0)
.reverse()
.join(" + ");
```
### 8、求數的約數的數組
>[warning] Create a function named `divisors/Divisors` that takes an integer and returns an array with all of the integer's divisors(except for 1 and the number itself). If the number is prime return the string '(integer) is prime' (null in C#) (use Either String a in Haskell and `Result<Vec<u32>, String>` in Rust).
**Example:**
```js
divisors(12); // should return [2,3,4,6]
divisors(25); // should return [5]
divisors(13); // should return "13 is prime"
```
>[warning] You can assume that you will only get positive integers as inputs.
我的解法:
```js
function divisors(integer) {
let r = [];
for(let i= 2;i<integer;i++){
if(integer%i == 0){
r.push(i);
}
}
return r.length == 0 ? `${integer} is prime` :r ;
};
```
別人的,循環次數直接減了一半:
```js
function divisors(integer) {
var res = []
for (var i = 2; i <= Math.floor(integer / 2); ++i) if (integer % i == 0) res.push(i);
return res.length ? res : integer + ' is prime'
};
```
### 9、數組排序
>[warning]Your task is to sort a given string. Each word in the String will contain a single number. This number is the position the word should have in the result.
Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).
If the input String is empty, return an empty String. The words in the input String will only contain valid consecutive numbers.
For an input: "is2 Thi1s T4est 3a" the function should return "Thi1s is2 3a T4est"
**Example:**
```js
your_order("is2 Thi1s T4est 3a")
[1] "Thi1s is2 3a T4est"
```
我的答案:
```js
function order(words){
var result=[];
words.split(' ').map(item=>{
if(!item) return false;
result[Number(item.match(/[1-9]/)[0])-1]=item;
});
return result.join(' ');
}
```
答案二,使用`sort`排序:
```js
function order(words){
return !words?'':words.split(' ').sort((a,b)=>+a.match(/\d/g)> +b.match(/\d/g)).join(' ')
}
```
關于`+`在這邊的使用可參考【Javascript篇】流水賬**。
### 10、數組按需過濾
>[warning] 原題有點長,我簡要描述下:給定數組,由`NORTH`,`SOUTH`,`WEST`,`EAST`四個值組成,眾所周知,`N`和`S`,`W`和`E`互為反方向。算法要求,數組中從前往后每個元素跟它下一個元素比較,如果為反方向,則將它們兩干掉(去除),返回剩下值的數組。
**栗子:**
```js
//1
輸入: ['SOUTH', 'NORTH', 'WEST', 'EAST', 'SOUTH']
輸出:['SOUTH']
//2.
輸入: ['SOUTH', 'WEST', 'NORTH', 'EAST']
輸出: ['SOUTH', 'WEST', 'NORTH', 'EAST']
```
這個問題理清楚算法是什么還是比較好解決的,關鍵一開始理解清楚算法,導致花了很長的時間。
我的解法,采用了一個遞歸,執行效率略差:
```js
const getOppsite = {
NORTH:'SOUTH',
SOUTH:'NORTH',
EAST:'WEST',
WEST:'EAST'
};
function dirReduc(plan) {
for(var i=0;i<plan.length;i++){
if(plan[i] == getOppsite[plan[i+1]]){
//拿當前元素與它后一個元素的反向進行比較,如果相同則截取掉它們兩個,
//返回的新數組遞歸重新比較
plan.splice(i,2);
dirReduc(plan);
}
}
return plan;
}
```
<div class="cline"></div>
對于`js`來講,這道題主要考察的應該是`Array`的高階函數`reduce`,關于`reduce`的描述已在【流水賬】中記錄了,這里不再贅述,簡要的講下概念:
>[success] `reduce()` 方法接收一個函數作為累加器,數組中的每個值(從左到右)開始縮減,最終計算為一個值。
```js
const getOppsite = {
NORTH:'SOUTH',
SOUTH:'NORTH',
EAST:'WEST',
WEST:'EAST'
};
function dirReduc(plan) {
return plan.reduce(function(result,current){
//這是這個方法的巧妙點,利用數組的最后一位來與當前值進行比較,
//剛好達到算法的要求。
if(result[result.length-1] == getOppsite[current]){
result.pop();
}else{
result.push(current);
}
return result;
},[]);
}
```
<div class="over"></div>
- 前端
- C1-Javascript
- H5圖片分塊和斷點續傳
- JavascriptPatterns[Stoyanstefanov]
- macotask和microtask
- 前端代碼生成器
- 跨域
- 頁面回到頂部滾動按鈕實現
- C2-CSS
- 瀏覽器的一些單位
- 盒模型
- 移動端判斷橫豎屏
- C3-框架
- ReactNative
- 開發環境搭建(安卓篇)
- Vue
- vue+pdfjs使用
- vue+typescript使用實踐
- vue+webpack3.x集成typescript
- Vue源碼3
- vue源碼分析1
- vue源碼分析2
- vue筆記
- C4-工具
- git
- Gitlab-CICD
- mock規則
- vscode-settings
- webpack自定義命令,切換代理地址
- 正則表達式
- 深入淺出webpack
- C5-Node
- express
- express源碼閱讀
- nightmare使用指南
- 爬蟲1.0
- C6-微信
- 微信
- C7-Canvas
- 基礎API
- 前端隨筆筆記
- 后端
- C1-Java
- shiro
- C2-Linux
- ffmpeg
- ITerm
- Linux
- MongoDB安裝
- MySql安裝
- Ngnix反向代理
- 常見錯誤
- 備忘
- mac
- 備忘-Work
- 備忘Link
- 服務器資源
- 教程
- Hexo個人博客搭建筆錄
- 文檔
- CSS編碼規范
- 前端編碼規范
- 隨筆
- 整理
- 正則
- 鏈接收藏
- 面試
- CodeWars題庫
- CodeWars題庫(二)
- Java社招面試題
- Java面試
- Web面試
- 前端筆試題
- 筆試題