数字,列表,字符串之间的转换
Facebook interviewers like this question and propose it in four main variations. The choice of algorithm should be based on the input format:
Strings . Use schoolbook digit-by-digit addition. Note, that to fit into constant space is not possible for languages with immutable strings, for example, for Java and Python. Here are two examples:
67.Add Binary: sum two binary strings.
415.Add Strings: sum two non-negative numbers in a string representation without converting them to integers directly.
Integers. Usually, the interviewer would ask you to implement a sum without using + and - operators. Use bit manipulation approach. Here is an example:
371.Sum of Two Integers: Sum two integers without using + and - operators.
Arrays. The same textbook addition. Here is an example:
989.Add to Array Form of Integer.
Linked Lists. Sentinel Head + Textbook Addition. Here are some examples:
66.Plus One.
2.Add Two Numbers.
445.Add Two Numbers II.
参考:
python 字符串(str)和列表(list)的互相转换
在Python中如何将整数转换为列表
[string - list]
168. Excel Sheet Column Title & 171. Excel Sheet Column Number/ 210715
按26取余
解法:从string中取字母拼list -> string
特例:余数为0时,个位为z,十位-1
字母转数更简单,没特例。
[int - string]
67. Add Binary /210629
这个题反而不能用遍历list。转为int做
解法:string -> int 相加 -> 二进制 ->string
return bin(int(a,2)+int(b,2))[2:]#bin返回字符串,要去掉尾部的‘0b’
return '{0:b}'.format(int(a, 2) + int(b, 2))#官方
415. Add Strings / 210701
由于不能转换成int,用手算加法的方法硬算,先转为list,每一位和进位相加,处理最后的进位,转为字符串
int(‘数字’)-int(‘0’)得到数字
371.Sum of Two Integers
[int - list]
989. Add to Array-Form of Integer / 210701
输入一个数字列表一个整数相加输出一个列表
解法:list->int + int -> list
官方解法:从个位开始,和整数相加,留下最后一位,前面部分加到前一位
特例:[0],10000 ->[1,0,0,0,0]
class Solution