Skip to content
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

反转一个 3 位整数 | 入门级-算法 #6

Open
OBKoro1 opened this issue Aug 1, 2019 · 0 comments
Open

反转一个 3 位整数 | 入门级-算法 #6

OBKoro1 opened this issue Aug 1, 2019 · 0 comments

Comments

@OBKoro1
Copy link
Owner

OBKoro1 commented Aug 1, 2019

博客链接

# 反转一个 3 位整数

# 描述:

反转一个只有 3 位数的整数

# 样例:

123 反转之后是 321。 900 反转之后是 9。

# 题目分析:

  • 009这种形式需要转为9
  • 最后输出的数字。

# 转数组操作:

这是最简单,最容易想到的答案:

  1. 数字转成字符串再转成数组
  2. 颠倒数组(翻转了),恢复成字符串
  3. 输出正常数字,这里用了+号。(用parseInt等也是可以的)
const reverseInteger = function(number) {
  return +[...number.toString()].reverse().join('');
};

# 取余数,逐个颠倒

const reverseInteger = function (number) {
    return parseInt(number%10)*100+parseInt((number%100)/10)*10+parseInt(number/100)*1
}

通过取余操作,个位转百位,十位转十位,百位转个位。

比如:123=>300+20+1,输出321

# 拼接字符串:

  • 数字转字符串
  • 从后往前取对应位置字符,拼接成一个颠倒的字符串
const reverseInteger = function(number) {
  var str = number.toString(); // 转字符
  return parseInt(str.charAt(2) + str.charAt(1) + str.charAt(0)); // 取对应位置字符,拼接成新的字符串
};

# 点个Star支持我一下~

博客链接

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant