确定整数是否可以表示为回文和

时间:2019-02-14 16:07:29

标签: javascript algorithm

在一次采访中有人问我这个问题:

  

如果整数可以表示为回文的和(与后向相同,则为整数),则为 special 。例如,22和121都是特殊的,因为22等于11+11和121等于29+92

     

给出一个整数数组,计算其中有多少个特殊元素。

但是我想不出任何解决方案。该怎么办?

8 个答案:

答案 0 :(得分:2)

在面试的压力和匆忙中,我肯定会找到一个愚蠢而幼稚的解决方案。

伪代码

loop that array containing the numbers
    Looping from nb = 0 to (*the number to test* / 2)
        convert nb to string and reverse the order of that string (ie : if you get "29", transform it to "92")
        convert back the string to a nb2
        if (nb + nb2 == *the number to test*)
            this number is special. Store it in the result array
    end loop
end loop
print the result array

function IsNumberSpecial(input)
{
    for (let nb1 = 0; nb1 <= (input / 2); ++nb1)
    {
        let nb2 = parseInt(("" + nb1).split("").reverse().join("")); // get the reverse number
        if (nb2 + nb1 == input)
        {
           console.log(nb1 + " + " + nb2 + " = " + input);
            return (true);
        }
    }
    return (false);
}

let arr = [22, 121, 42];

let len = arr.length;
let result = 0;

for (let i = 0; i < len; ++i)
{
    if (IsNumberSpecial(arr[i]))
        ++result;
}

console.log(result + " number" + ((result > 1) ? "s" : "") + " found");

答案 1 :(得分:2)

在伪代码中,这是一个非常幼稚的解决方案,用于确定数字是否为“特殊”:

Given an number N (assumed to be an integer)
Let I = Floor(N / 2)
Let J = Ceil(N / 2)
While (I > 0)
    If I is the reverse of J Then
        Return True
    End
    I <- I - 1
    J <- J + 1
End
Return False

一个快速的JS实现:

function isSpecial(n) {
  for (var i = Math.floor(n / 2), j = Math.ceil(n / 2); i > 0; i--, j++) {
    console.info(`checking ${i} + ${j}`);
    if (i.toString().split('').reverse().join('') === j.toString())
      return true;
  }

  return false;
}

console.log(isSpecial(121));

我将留给您实现函数以对数组中的特殊数字进行计数。可以通过改进相当粗略的字符串反转检查方法,或者通过更智能地跳过数字来提高效率。

答案 2 :(得分:1)

一些伪代码?

num_special = 0

for item in array:
  for num in range(1, total):
    if num + int(string(num).reversed()) == item
      num_special += 1
      break

print(num_special)

编辑:

这是一个有效的Python示例:

array = [22, 121]

num_special = 0

for item in array:
  for num in range(1, item):
    if (num + int(str(num)[::-1]) == item):
      num_special += 1
      break

print(num_special)

https://repl.it/repls/UsedLovelyCategory

答案 3 :(得分:1)

假设我们想要两个求和项-这个问题似乎没有指定,但是每个答案都假定了!

(没有这种假设,每个数字都可以写成1 s的可逆总和。)

一位数求和:

n is even

两位数求和:

10x + y + 10y + x

11x + 11y

11(x + y)

n is divisible by 11

三位数求和:

100x + 10y + z + 100z + 10y + x

101x + 20y + 101z

101(x + z) + 20y

more complex but we can still
do better than a brute force
loop of 1 to n / 2

等...(我们可能可以编写一个泛化并搜索此代数的函数)

更新

JavaScript代码(有趣的是,蛮力1到n / 2循环似乎更快地找到了1111111110的结果!也许可以进行其他一些优化):

function f(n){
  let start = new Date;
  let numDigits = 0;
  let t = Math.ceil(n / 2);
  while (t){
    numDigits++;
    t = ~~(t/10);
  }
  
  // Summands split between x and x+1 digits
  if (n / 2 + 0.5 == Math.pow(10, numDigits - 1))
    return false;

  let cs = [];
  let l = Math.pow(10, numDigits - 1);
  let r = 1;
  
  while (l >= r){
    cs.push(l + r);
    l /= 10;
    r *= 10;
  }
  
  let sxs = new Array(cs.length);
  const m = cs.length & 1 || 2;
  sxs[cs.length-1] = m*cs[cs.length-1];
  for (let i=cs.length-2; i>=0; i--)
    sxs[i] = 2*cs[i] + sxs[i + 1];
  
  let stack = [[0, n, []]];
  let results = [];

  while (stack.length){
    let [i, curr, vs] = stack.pop();

    if (i == cs.length - 1){
      let d = curr / cs[i];

      if (d == ~~d && 
        ((cs.length & 1 && d < 10) || ((!(cs.length & 1) || cs.length == 1) && d < 19)))
        results.push(vs.concat('x'));
      continue;
    }
    
    t = 2;
    curr -= t*cs[i];
    stack.push([
      i + 1, curr,
      vs.slice().concat(t)]);
    
    while (curr >= sxs[i + 1]){
      curr -= cs[i];
      stack.push([
        i + 1, curr,
        vs.slice().concat(++t)]);
    }
  }
  let time = new Date - start;
  return [!!results.length, (time) + 'ms', cs, results];
}

let ns = [
  22, 121, 42,
  66666,
  777777,
  8888888,
  99999999,
  68685,
  68686]

for (let n of ns)
  console.log(n, JSON.stringify(f(n)));

答案 4 :(得分:0)

我的 JS 变体:

const reverseInt = (n) =>
    parseInt(n.toString().split('').reverse().join(''))

const checkSpecialInt = (n) =>{
    for(let i=1;i<=n;i++){
        if (i+reverseInt(i)==n) return true;
    }
    return false;
}
const checkSpecialIntArray = (arr) => 
    arr.filter((e,i)=>checkSpecialInt(e)).length;

let test = [122, 121, 22, 21];
console.log(checkSpecialIntArray(test));

答案 5 :(得分:0)

该要求不包括返回匹配的“特殊数字”的所有可能组合,只是找到一个匹配项。

const isSpecialInteger = arr => {
  // `arr`: `Array`
  // result, initialized to `0`
  let res = 0; 
  // iterate input `arr`
  for (let n of arr) {
    // divide `n` by `2`
    const c = n / 2;
    // check if `n` is an integer or decimal
    // if decimal subtract decimal portion of 1st divided decimal
    // add decimal portion to 2nd portion of divided decimal
    // else set `x`, `y` to even division of input `n`
    let [x, y] = !Number.isInteger(c) ? [c - (c % 10), c + (c % 10)] : [c, c];
    // set label for `for` loop
    // decrement result of `Math.max(x, y)` 
    N: for (let i = Math.max(x, y); i; i--) {
      // check if `i` converted to
      // string, then array reveresed
      // if equal to `n`
      // if `true` increment `res` by `1` `break` `N` loop
      if (i + +[...`${i}`].reverse().join`` === n) {
        res+= 1;
        break N;
      } 
    }
  }
  // return positive integer or `0`
  return res;
}

console.log(
  isSpecialInteger([22, 121])
);

答案 6 :(得分:0)

这是 JAVA 中的一种蛮力方法,可以进一步优化,

import java.util.Scanner;

公开课解决方案 {

public static void main(String[] args)
{
    Scanner in = new Scanner(System.in);
    
    String str = in.nextLine();
    String[] inp = str.split(",");
    
    System.out.println(isSpecial(inp,inp.length));
}

public static int isSpecial(String[] inp, int inpSize) 
{
    int arr[] = new int[inp.length];
    for(int i=0;i<inpSize;i++) 
    {
        arr[i] = Integer.parseInt(inp[i]);
    }
    
    int spclCount = 0;
    for(int i=0;i<arr.length;i++) 
    {
        for(int j=1;j<((arr[i]/2)+1);j++) 
        {
            if(j+getReverse(j) == arr[i]) 
            {
                spclCount++;
                break;
            }
        }
    }
    
    return spclCount;
}

public static int getReverse(int n) 
{
    int rem,rev=0;
    while(n != 0)
    {
        rem = n % 10;
        rev = (rev*10) + rem;
        n /= 10;
    }
    return rev;
}

}

答案 7 :(得分:-1)

问题:

一个整数是特殊的,如果它可以表示为一个回文的总和(向后与向前相同)。比如22和121都是特殊的,因为22等于11+11,121等于29+92。

给定一个整数数组,计算其中有多少特殊元素

我的方法:

public class PalindromicSum {

    public static void getSplNumber(int[] arrip) {
        //to iterate i/p array
        for (int i = 0; i < arrip.length; i++) {
            int tempSum = 0;
            //to iterate from 1 to number/2
            for (int j = 1; j <= arrip[i] / 2; j++) {
                //to get the reverse of the number
                int revNum = getRevNum(j);
                tempSum = revNum + j;
                if (tempSum == arrip[i]) {
                    System.out.println(arrip[i]);
                    break;
                } 
            }
        }
    }

    public static int getRevNum(int num) {
        int rev = 0;
        //to get reverse of a number
        while(num!=0) {
            int reminder = num%10;
            rev = rev*10 + reminder;
            num = num/10;
        }
        return rev;
    }

    public static void main(String[] args) {
        int[] arr = { 121, 11, 10, 3, 120, 110};
        getSplNumber(arr);

    }

}
相关问题