10道单选题
10道多选题
2道编程题

第一题:十进制转二进制计算1的个数(负数转为补码)

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/8/23 15:44
# @Author  : @linlianqin
# @Site    : 
# @File    : 十进制转换为二进制(计数1的个数).py
# @Software: PyCharm
# @description:

class Solution:
	def oct_to_binary(self, input_int):
		# write code here
		tag = True
		if input_int == 0:
			return 0
		if input_int < 0:
			tag = False
		abs_int = abs(input_int)
		# 原码
		bin_int = list(bin(abs_int)[2:])
		bin_int = ["0" for _ in range(32 - len(bin_int))] + bin_int
		if tag:
			return bin_int.count("1")
		else:
			# 反码
			reverse_bin_int = ["0" for _ in range(32)]
			for index, i in enumerate(bin_int):
				if i == "0":
					reverse_bin_int[32-len(bin_int)+index] = "1"
			# 补码
			res = ""
			resual = True
			for index,i in enumerate(reverse_bin_int[::-1]):
				if i == "0":
					if resual:
						res = "1"+res
					else:
						res = "0"+res
					resual = False
				elif i == "1":
					if resual:
						res = "0" + res
						resual = True
					else:
						res = "1" + res
			if resual:
				res = "1" + res
			return res.count("1")

print(Solution().oct_to_binary(-5))

第二题:字符串转为驼峰

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/8/23 16:21
# @Author  : @linlianqin
# @Site    : 
# @File    : 输入的字符串转换为驼峰.py
# @Software: PyCharm
# @description:
'''
详细描述
1. 转换后的字符串只保留字母[a-zA-Z]和数字[0-9],去除其他字符;
2. 输入字符串中的字母字符的前一字符如非字母或数字,该字母转换后为大写,如果前一个字符为字母或者数字,字母转换后为小写;
例外:转换后的字符串第一个字符如果是字母,则该字母转换后为小写;——字符串首字母小写
3. 转换后的字符串保留数字字符。
4. 字符串如果为空或者无[a-zA-Z]和数字[0-9]中字符,请默认输出如下字符串"shopee"
'''


class Solution:
	def camelCase(self, newString):
		# write code here
		strLen = len(newString)
		# 字符串为空
		if strLen == 0:
			return "shopee"
		# 字符串不为空
		res = []
		for index,code in enumerate(newString):
			# 是字母或者数字
			if code.isalnum():
				if index == 0:
					if code.isdigit():
						res.append(code)
					else:
						res.append(code.lower())
					continue
				# 前一个是字母和数字时:
				if index >= 1 and newString[index-1].isalnum():
					if code.isdigit():
						res.append(code)
					else:
						res.append(code.lower())
				# 前一个不是字母和数字时
				elif index >= 1 and not newString[index - 1].isalnum():
					if code.isdigit():
						res.append(code)
					else:
						res.append(code.upper())
		#处理第一个字符
		if len(res) == 0:
			return "shopee"
		else:
			if res[0].isalpha():
				res[0] = res[0].lower()
			res = "".join(res)
			return res

print(Solution().camelCase("__HELLO_World"))
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐