找出下面代码的规律并且编写一个函数,转换特定的整数到对应的字符串。
1 => A,2 => B,3 => C,...,26 => Z,27 => AA,28 => AB,29 => AC,...,52 => AZ,53 => BA,...
function convert (num) {
}
convert函数怎么写?这道题怎么做?有会的吗?
巴扎黑2017-04-11 12:46:31
function convert(num){
var result = [];
while(num){
var t = num % 26;
if(!t){
t = 26;
-- num;
}
result.push(String.fromCodePoint(t + 64));
num = ~~(num / 26);
}
return result.reverse().join('');
}
这是不是leetcode上面的。。
天蓬老师2017-04-11 12:46:31
总而言之一句话:
function convert(num){
return num <= 26 ?
String.fromCharCode(num + 64) : convert(~~((num - 1) / 26)) + convert(num % 26 || 26);
}
巴扎黑2017-04-11 12:46:31
这样可以吗
function convert (num) {
var s = ''
while (num > 0) {
var m = num % 26
if (m === 0) m = 26
s = (m + 9).toString(36) + s
num = (num - m) / 26
}
return s.toUpperCase()
}
大家讲道理2017-04-11 12:46:31
function convert(num) {
var saveLet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
var singleLet = "";
var val = 0;
while (num > 0) {
val = (num-1) % 26
singleLet = saveLet[val] + singleLet;
num = Math.floor((num-1) / 26);
}
return singleLet;
}
ringa_lee2017-04-11 12:46:31
function convert (num) {
var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var len = str.length;
var carry = num;
var ret = [];
if (!num || num < 0) {
return;
}
do{
var unit = carry % len;
if (!unit) {
carry = carry -1;
unit = len;
}
ret.unshift(str.charAt(unit-1));
if (carry && carry>0) {
carry = Math.floor(carry/len)
}else{
carry = 0
}
}
while (carry);
return ret.join('');
}
天蓬老师2017-04-11 12:46:31
// 字符串转数字 利用ascill 数字转字符也可以用这种吧
function convert(str) {
var count = 0;
var strArray = str.toUpperCase().split('');
strArray.forEach(function(item, index) {
count += item.charCodeAt() - 64 + index*25;
})
return count
}
高洛峰2017-04-11 12:46:31
function convert(n) {
var s = '';
while (n>0) {
var m = n % 26;
if (m==0) m = 26;
s = String.fromCharCode(m + 64) + s;
n = (n - m) / 26;
}
return s;
}
迷茫2017-04-11 12:46:31
应该是这道题吧 https://leetcode.com/problems...,AC 代码 https://github.com/hanzichi/l...