-
-
Save mpr0xy/ca75d56e92d1a837c4214adcc29e8331 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ip(str) { | |
var length = str.length; | |
var ans = []; | |
var stack = []; | |
var step = 0; | |
var lastStep = 0; | |
var lastchar = '' | |
// 生成原始数组 | |
for (var i = 0; i < 32; i++) { | |
ans[i] = 0; | |
} | |
// 处理每一次相加 | |
function handle() { | |
if (stack.length === 0) { | |
if (lastchar === 'b') { | |
ans[step] = 1; | |
} else { | |
ans[step] = 0; | |
} | |
step++; | |
} else { | |
var nStep = 0; | |
stack.forEach(function(item, index) { | |
if (index === 0) { | |
nStep += item; | |
} | |
if (index === 1) { | |
nStep += (10 * item) | |
} | |
}); | |
if (lastchar === 'b') { | |
for (var i = step; i < step + nStep; i++) { | |
ans[i] = 1; | |
} | |
} else { | |
for (var i = step; i < step + nStep; i++) { | |
ans[i] = 0; | |
} | |
} | |
step += nStep; | |
} | |
} | |
for (var i = length - 1; i >= 0; i--) { | |
// 每次处理一次变更 | |
if ((str[i] === 'a' || str[i] === 'b') && i != (length - 1)) { | |
handle(); | |
stack = []; | |
} | |
if (str[i] === 'a' || str[i] === 'b') { | |
lastchar = str[i]; | |
} else { | |
stack.push(Number(str[i])); | |
} | |
} | |
handle(); | |
console.log(ans.join('')); | |
var ips = []; | |
// 把数组转换城字符输出 | |
for (var i = 0; i < 4; i++) { | |
var temp = 0 | |
for (var j = 0; j < 8; j++) { | |
if (ans[i * 8 + j] === 1) { | |
temp += Math.pow(2, j); | |
} | |
} | |
ips[i] = temp; | |
} | |
return ips[3] + '.' + ips[2] + '.' + ips[1] + '.' + ips[0]; | |
} | |
var ans = ip('7ab7ab7a2b6ab'); | |
console.log(ans); | |
console.log(ans === '1.1.1.129'); | |
var ans = ip('32a'); | |
console.log(ans); | |
var ans = ip('32b'); | |
console.log(ans); | |
var ans = ip('8b8a8b8a'); | |
console.log(ans); | |
var ans = ip('a7b8a8a7ab'); | |
console.log(ans); | |
var ans = ip('aa6baa6baa6b8a'); | |
console.log(ans); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment