# javascript实现一些算法题

## 字符的左右移动

``````var stars = 'sosunn**afns*repsni*';

var rs = stars.split('');
var flag = 0;
for(var i=rs.length -1; i>=0; i--){
if(rs[i] == '*'){
flag++;
}else{
if(flag == 0)
continue;
else{
rs[i+flag] = rs[i];
rs[i] = '*';
}
}
}
console.log(rs.join(''))``````

## map妙用

``````var str = 'safaAuasfAJIFjHDWEFHDaAueUEWda';
var results = {};
var rs = str.split('');

rs.forEach(function(al){
if(results[al] === undefined){
results[al] = 1;
}else{
results[al]++;
}
})

var keys = Object.keys(results);
for(var i = 0; i < keys.length; i++){
console.log(keys[i] + ' : ' + results[keys[i]]);
}``````

``````var str = 'abaccdefbf';
var results = {};
var rs = str.split('');

rs.forEach(function(al){
if(results[al] === undefined){
results[al] = 1;
}else{
results[al]++;
}
})

var keys = Object.keys(results);
for(var i = 0; i < keys.length; i++){
if(results[keys[i]] === 1){
console.log(keys[i]);
break;
}
}``````

``````var json1 = { ... };
var jmap = {};
var result = [];

json1.forEach(function(al){
var key = al.menuDate + '_' + al.dinnerTime;
if(typeof jmap[key] === 'undefined'){
jmap[key] = [];
}
jmap[key].push(al);
})

var keys = Object.keys(jmap);
for(var i = 0; i < keys.length; i++){
var rs = keys[i].split('_');
}``````

## 位运算

1.乘除模拟位运算：

``````(function(aInt){
var intStr = [], count = 1;
while(aInt > 1){
if(aInt % 2 == 0){
intStr.unshift(0);
}else{
intStr.unshift(1);
count++;
}
aInt = Math.floor(aInt/2);
}
intStr.unshift(1);

console.log('Binary String : ' + intStr.join(','));
console.log('The count is  : ' + count);
}(28));``````

2.真正位运算：

``````(function(aInt){
var intStr = [], count = 0;
while(aInt > 0){
var cur = aInt & 1;
intStr.unshift(cur);
if(cur == 1){
count++;
}
aInt = aInt >> 1;
}

console.log('Binary String : ' + intStr.join(','));
console.log('The count is  : ' + count);
}(10));``````

``````(function(aInt){
var count = 0;
for(var i = 1; i <= aInt; i++){
var a = i;
while(a >= 1){
if(a % 10 == 1){
count++;
}
a= Math.floor(a / 10);
}
}
console.log('The count is  : ' + count);
}(13));``````

#### 你可能感兴趣的

1 条评论
liuhongyi0101 · 2018年03月27日