牛牛想对一个数做若干次变换,直到这个数只剩下一位数字。 变换的规则是:将这个数变成 所有位数上的数字的乘积。比如285经过一次变换后转化成285=80. 问题是,要做多少次变换,使得这个数变成个位
牛牛想对一个数做若干次变换,直到这个数只剩下一位数字。
变换的规则是:将这个数变成 所有位数上的数字的乘积。比如285经过一次变换后转化成285=80.
问题是,要做多少次变换,使得这个数变成个位数。
输入描述:
输入一个整数。小于等于2,000,000,000。
输出描述:
输出一个整数,表示变换次数。
输入例子:
285
输出例子:
2
public class Main2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String st = sc.nextLine();
int len = st.length();
/*if(len == 1){
System.out.println(1);
return;
}*/
int cnt = 0;
while (true){
long sum = 1;
cnt++;
len = st.length();
for(int i = 0; i < len; i++){
sum *= (st.charAt(i) - '0');
if(sum == 0){//一旦出现0,及时终止,输出即可
System.out.println(cnt);
return;//特判,有可能在相乘过程已经为0,
}
}
if(sum < 10){
System.out.println(cnt);
return;//这个命令可以及时终止
}
st = new String(sum + "");
}
}
}
将单链表的每K个节点之间逆序
https://www.nowcoder.com/questionTerminal/66285653d28b4ed6a15613477670e936?orderByHotValue=1&page=1&onlyReference=false
给定一个单链表,实现一个调整单链表的函数,使得每 K 个节点之间的值逆序,如果最后不够 K 个节点一组,则不调整最后几个节点。
输入描述: 第一行一个整数 n,n 表示单链表的节点数量。
第二行 n 个整数 val 表示链表的各个节点的值。
第三行一个整数 K。
输出描述: 在给定的函数内返回链表的头指针。
输入
5
1 2 3 4 5
3
输出
3 2 1 4 5
先尝试一下c++的版本
属于计数方法,每次计数达到k就反转一下
import java.util.*;
class Node{
int val;
Node next;
public Node(int data){
this.val = data;
this.next = null;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
//还是先指定一个暂时的头结点
Node head = new Node(-1);
Node cur = head;
for(int i = 0; i < n; i++){
int tmp = sc.nextInt();
cur.next = new Node(tmp);
cur = cur.next;
}
int k = sc.nextInt();
Node result = reverseGroup(head.next, k);
while (result != null){
System.out.print(result.val + " ");
result = result.next;
}
}
public static Node reverseGroup(Node head, int k){
if(k < 2) return head;
Node start = null;
Node pre = null;
Node cur = head;
Node next = null;
int cnt = 1;
while(cur != null){
next = cur.next;
if(cnt == k){//这个时候保证长度是k,获取开始结束的地址,进行反转
//此时cur恰为第k个节点,next为下一个节点
start = (pre == null ? head : pre.next);//pre.next用来记录每次反转单元的开始
head = (pre == null ? cur : head);//head用来记录最终的返回头节点,只赋值一次
Node n1 = start, n2 = start.next, n3 = null;
//n1, n2, n3来负责移动和反转
while(n2 != next){//每两个节点移动反转,即n2 == cur还是需要反转的
n3 = n2.next;//先保存下来
n2.next = n1;
n1 = n2;
n2 = n3;
}
//同时把每一段都连上
//pre记录的是上一段反转之后的最后一个节点, start记录的是当前段反转之后的最后一个节点
if(pre != null) pre.next = cur;//连接前后两段
start.next = next;//也就是说每反转一个节点,都要维护好前后两段的连接
//更新pre
pre = start;
cnt = 0;//再次更新为0;
}
cnt++;
cur = next;
}
return head;
}
}