-
Notifications
You must be signed in to change notification settings - Fork 3.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
第 81 题:打印出 1 - 10000 之间的所有对称数 例如 121、1331 等 #131
Comments
是下标
…------------------ 原始邮件 ------------------
发件人: "robbie"<notifications@github.com>;
发送时间: 2019年5月24日(星期五) 上午9:17
收件人: "Advanced-Frontend/Daily-Interview-Question"<Daily-Interview-Question@noreply.github.com>;
抄送: "Subscribed"<subscribed@noreply.github.com>;
主题: Re: [Advanced-Frontend/Daily-Interview-Question] 第 81 题:打印出 1 - 10000 之间的所有对称数 例如:121、1331 等 (#131)
第 81 题:打印出 1 - 10000 之间的所有对称数
例如:121、1331 等
[...Array(10000).keys()].filter((x) => { return x.toString().length > 1 && x === Number(x.toString().split('').reverse().join('')) })
为什么控制台会有一个[0,99],一个[100,188]两个数组?
—
You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub, or mute the thread.
|
var result = [];
for (let i = 1; i <= 10000; i++) {
let origin = '' + i;
let reverse = origin.split('').reverse().join('');
if(origin === reverse) {
result.push(i);
}
} |
|
for(let i = 1; i <= 10000; i++)
if(isPalindrome(i))
console.log(i);
var isPalindrome = function(x) {
if((x < 0) || (x !== 0 && x % 10 === 0))
return false;
let tmp = 0;
while(x > tmp) {
tmp = tmp * 10 + x % 10;
x = Math.floor(x / 10);
}
return x === tmp || x === Math.floor(tmp / 10);
}; |
|
//第 81 题:打印出 1 - 10000 之间的所有对称数 例如:121、1331 等
class Test{
constructor() {
this.arr = [];
}
symmetry() {
for(var i = 1; i<=1000;i++) {
let flag = true;
i = String(i);
let integer = parseInt(i.length/2);
for(let j = 0; j < integer; j++) {
if(i[j] != i[i.length - j -1]) {
flag = false
}
}
if(flag) {
this.arr.push(Number(i))
}
}
return this.arr;
}
}
let test = new Test();
console.log(test.symmetry()) //[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242, 252, 262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363, 373, 383, 393, 404, 414, 424, 434, 444,....] |
|
@zpzxgcr
假如说现在改为 1 - 9999的话,不加 |
Array.from({length:10000},(v,i) => i+1).slice(9).filter(item => (item+'').split('').reverse().join('') === (item+'')); |
function test(num) {
let str = num + '';
var l = str.length;
for (let i = 0; i < Math.ceil(l / 2); i++) {
if (str.charAt(i) !== str.charAt(l - i - 1)) {
return false;
}
if ((i === (l - i - 1)) || i === l - i - 2) {
console.log(str);
}
}
}
for (let i = 0; i < 10000; i++) {
if (i > 10 && i % 10 !== 0) {
test(i);
}
} |
function printSymmetry(begin: number, end: number) {
const isSymmetry = (str: string) => str === Array.from(str).reverse().join('');
Array.from({length:end}, (_, index) => index)
.filter(v => v>begin && isSymmetry(String(v)))
.forEach(v => console.log(v));
}
printSymmetry(1, 10000); |
[...Array(10000).keys()].filter((x) => {
return x > 10 && x.toString() === x.toString().split('').reverse().join('');
}) |
返回一个数组,其值为所有符合条件的数字。 // 方法一
[...Array(10000).keys()].filter(i => i.toString().length > 1 && i == i.toString().split('').reverse().join(''))
// 方法二
[...Array(10000).keys()].filter(i => i > 10 && i == [...i + ''].reverse().join('')) |
咋全是遍历所有数字的答案。 以10000 为例,列出所有位数的对称数,比如1位数的 对称数, 2位数的对称数...到5位数, 再判断是否小于10000。 对称数生成 : 遍历最长位数(如5位)。 每个位置遍历 0 - 9,对称即可。 |
let result=[]
for(let i=1;i<10;i++){
result.push(i)
result.push(i*11)
for(let j=0;j<10;j++){
result.push(i*101+j*10)
result.push(i*1001+j*110)
}
} 没必要去遍历10000个数 |
呀,我们是黑白配。我第一眼的想法并不是循环数组而是去构造所有的对称数,大于10000的时候停止 |
方法一[...Array(10000).keys()].filter(x => x.toString().length > 1 && x === Number([...x.toString()].reverse().join(''))) 方法二for(let i=0; i<10000; i++){
let str = i.toString()
if(str.length>1 && str == [...str].reverse().join('')){
console.log(Number(str))
}
} |
笨方法实现
|
大家的方法都差不多,ES6还是好用。
|
function getSemmetryNum() { 两头肯定是类似1**1 2*2之类的,中间的数有可能是0位,1位,2位 这个方法可以得到结果,但不够通用 |
暴力解法
|
强答: [...Array(10000).keys()].filter(num => {
const len = ('' + num).length
if (len === 1) return true
return (
'' + num ===
('' + num)
.split('')
.reverse()
.join('')
)
}) |
// the first solution
const symmetry0 = (min, max) => {
let res = [];
for(let i = min; i <= max; i ++) {
if(i.toString().length > 1 && i.toString().split('').reverse().join('') === i.toString()) {
res.push(i);
}
}
return res;
}
console.log(symmetry0(1, 10000));
// the second solution
const symmetry = (min, max) => {
let arr = Array.from({length: max - min + 1}, (item, index) => index += min);
return arr.filter(item => item.toString().split('').reverse().join('') === item.toString());
}
console.log(symmetry(1, 10000)); |
1 - 9 应该不能算对称数吧 |
|
for (let i = 0; i < 100000; i++) { |
;[...Array(10000).keys()].filter((v) => {
return v === Number( (String(v).match(/(^\d)(\d)?\2*\1$/) || [])[0] )
})
精简一下
;[...Array(10000).keys()].filter(v => {
return (String(v).match(/(^\d)(\d)?\2*\1$/) || [])[0]
})
再精简一下
;[...Array(1e4).keys()].filter(v => (v+'').match(/(^\d)(\d)?\2*\1$/)) |
Array.from({length: 10000}, (o, i) => i).filter(o => o + '' === (o + '').split('').reverse().join('')) |
var result = '' |
|
function test(n) {
let arr = [];
for (let i = 10; i < n; i += 1) {
let str = i.toString();
if (str === str.split('').reverse().join('')) {
arr.push(i)
}
}
return arr;
}
test(10000) |
来个好看懂的,话说1到9不算对称数吧 |
Array.from({length: 10000}, (_, index) => index + 1).filter(item => item > 9 && item == String(item).split('').reverse().join('')) |
function fn(number){
let len = number < 10 ? 1 : ~~Math.log10(number);
let arr = Array.from({ length: len });
arr[0] = [''];
arr[1] = [];
for(let i = 0; i <= 9; i ++){
arr[1].push(i + '');
}
let index = 2;
while(index <= len){
arr[index] = [];
for(let i = 0; i <= 9; i ++){
for(let j of arr[index-2]){
arr[index].push(`${i}${j}${i}`);
}
}
index ++;
}
arr = arr.flat(2).filter(item => {
return item.length > 1 && item[0] !== '0';
});
return arr;
} |
我们没有必要遍历所有数,只需遍历1-99就行了,
` |
|
|
|
// 打印出 1 - 10000 之间的所有对称数
// 例如:121、1331 等
const logSymmetry = () => {
let result = [];
for (let i = 0; i < 10000; i++) {
let str = String(i);
let reverse = str.split("").reverse().join("");
if (str === reverse) {
result.push(i);
}
}
return result;
};
console.log(logSymmetry());
|
|
function a(start, end) {
} |
|
一个比较原始的办法,但却是最好理解的:
|
|
|
一、遍历所有数,判断是否是回文数1、字符串反转后判断 function isPalindrome(n) {
if (typeof n !== 'string') {
n = n.toString()
}
return n.split('').reverse().join('') === n
} 2、双指针遍历 function isPalindrome(n) {
if (typeof n !== 'string') {
n = n.toString()
}
let l = 0, r = n.length - 1
while(l <= r) {
if (n[l] !== n[r]) {
return false
}
l++
r--
}
return true
} function getPalindromeNumber(length) {
return Array.from({ length }, (v, i) => i + 1).filter((n) => {
return isPalindrome(n)
})
}
getPalindromeNumber(10000) 二、不遍历所有数,直接找出规律,枚举所有对称数function getPalindromeNumber() {
let res = []
for(let i = 1; i < 10; i++) {
res.push(i)
res.push(11 * i)
for(let j = 0; j < 10; j++) {
res.push(i * 101 + j * 10)
res.push(i * 1001 + j * 110)
}
}
return res
} |
正则表达式,顺便对比一楼的耗时 //正则表达式
console.time('s')
var reg = /^(\d)\1$|^(\d)\d\2$|(\d)(\d)\4\3/g
var arr = [];
for(var i = 1; i <= 10000; i++){
var v = reg.exec(String(i))
if(v){
arr.push(Number(v[0]))
}
}
console.log(arr)
console.timeEnd('s')//s: 3.13916015625 ms
//
console.time('t')
var arr1 = Array(10000).keys();
console.log([...arr1].filter((x) => {
return x.toString().length > 1 && x === Number(x.toString().split('').reverse().join(''))
}))
console.log(arr1)
console.timeEnd('t')//t: 6.968017578125 ms |
这个字符串反转比较应该是用的最多的了吧 |
// 最小循环次数。
// 里面的关键系数 100 和 10 和 1 都是可以计算出来的,懒得搞直接写死
// 10000 本身不对称,于是最大对称就变成 9999,从中劈开就是 99 次循环生成镜像
// 但镜像长度是复数,因此要对奇数长度做额外处理
var arr = [];
for (let i = 1; i<100; i++) {
let reversedNum = String(i).split('').reverse().join('')
arr.push(i + reversedNum);
if ( i < 10 ) {
for(let j=0; j<10; j++) {
arr.push(i + '' + j + reversedNum);
}
}
};
/* 结果:
(189) ["11", "101", "111", "121", "131", "141", "151", "161", "171", "181", "191", "22", "202", "212", "222", "232", "242", "252", "262", "272", "282", "292", "33", "303", "313", "323", "333", "343", "353", "363", "373", "383", "393", "44", "404", "414", "424", "434", "444", "454", "464", "474", "484", "494", "55", "505", "515", "525", "535", "545", "555", "565", "575", "585", "595", "66", "606", "616", "626", "636", "646", "656", "666", "676", "686", "696", "77", "707", "717", "727", "737", "747", "757", "767", "777", "787", "797", "88", "808", "818", "828", "838", "848", "858", "868", "878", "888", "898", "99", "909", "919", "929", "939", "949", "959", "969", "979", "989", "999", "1001", …]
*/ |
function dd(num,list){ |
let res = [] function tt(str) {
} |
function symmetry(base = 10000) {
const res = []
for (let i = 1; i <= base; i++) {
const curReverse = (i + '').split('').reverse().join('')
if (i == curReverse && curReverse.length != 1) {
res.push(i)
}
}
return res.join(',')
}
console.log(symmetry()); |
普适解法,非暴力,求出1到任意数之间的对称数 function symmetry(max) {
let arr = []
out: for (let i = 1, len = Math.ceil(max.toString().length / 2); i <= len; i++) {
let start = Math.pow(10, i - 1)
// 奇数构造
for (let j = start; j < start * 10; j++) {
let s = j.toString(), // 左半边
reve = s.split('').reverse().slice(1).join(''), // 右半边
sy = parseInt(s + reve) // 合起来
if (sy > max) break out
arr.push(sy)
}
// 偶数构造
for (let j = start; j < start * 10; j++) {
let s = j.toString(), reve = s.split('').reverse().join(''), sy = parseInt(s + reve)
if (sy > max) break out
arr.push(sy)
}
}
return arr
} |
const isSymmetry = num =>
num > 10 && `${num}` === [...`${num}`].reverse().join('')
const printSymmetry = num => {
const symmetryList = []
Array.from({length: num }).forEach((_, index) => {
isSymmetry(index) && symmetryList.push(index);
});
console.log(symmetryList.join(','));
}
printSymmetry(10000); |
function isPalindrome(num) { function printPalindromes(range) { // 打印1到10000之间的所有对称数 |
const fn = (num) => { |
第 81 题:打印出 1 - 10000 之间的所有对称数
例如:121、1331 等
The text was updated successfully, but these errors were encountered: