package cloud.cue.group.util; import java.util.Random; /** * @Author xingmengyuan * @Date 2023/5/30 */ public class demo { public static void main(String[] args) { String random = getRandom(7); System.out.println("交换前:"+ random); Integer max = 0; char[] charsA = random.toCharArray(); char[] charsB = random.toCharArray(); for (int i = 0; i < random.length(); i++) { char temp = charsA[i]; if(temp == 0){ continue; } for (int j = i+1; j < random.length(); j++) { if(temp == charsA[j]){ continue; } charsB[i] = charsA[j]; charsB[j] = temp; String tempNum = new String(charsB); Integer newNum = Integer.valueOf(tempNum); if (max.compareTo(newNum) < 0) { max = newNum; } //还原比较对象 charsB = random.toCharArray(); //System.out.println("有效交换次:"+newNum); } } System.out.println("交换后:" + max); } public static String getRandom(int len) { int digit = (int) Math.pow(10, len - 1); int rs = new Random().nextInt(digit * 10); if (rs < digit) { rs += digit; } return String.valueOf(rs); } } 转换成python
时间: 2024-02-15 21:29:04 浏览: 159
import random
def get_random(len):
digit = 10 ** (len - 1)
rs = random.randint(digit, digit * 10 - 1)
if rs < digit:
rs += digit
return str(rs)
def main():
random_str = get_random(7)
print("交换前:" + random_str)
max_num = 0
chars_a = list(random_str)
chars_b = list(random_str)
for i in range(len(random_str)):
temp = chars_a[i]
if temp == '0':
continue
for j in range(i + 1, len(random_str)):
if temp == chars_a[j]:
continue
chars_b[i] = chars_a[j]
chars_b[j] = temp
temp_num = ''.join(chars_b)
new_num = int(temp_num)
if max_num < new_num:
max_num = new_num
# 还原比较对象
chars_b = list(random_str)
# print("有效交换次:" + str(new_num))
print("交换后:" + str(max_num))
if __name__ == '__main__':
main()
阅读全文