题目描述
小明对数位中含有 2、0、1、9 的数字很感兴趣(不包括前导 0),在 1 到 40 中这样的数包括 1、2、9、10 至 32、39 和 40,共 28 个,他们的和是 574。
请问,在 1 到 n 中,所有这样的数的和是多少?
输入格式
共一行,包含一个整数 n。
输出格式
共一行,包含一个整数,表示满足条件的数的和。
#include <iostream>
using namespace std;
int ans, n;
bool check(int n)
{
while (n)
{
int tmpn = n % 10;
if (tmpn == 2 || tmpn == 0 || tmpn == 1 || tmpn == 9)
return true;
__________________;
}
return false;
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
{
if (check(i))
ans += i;
}
cout << ans << endl;
return 0;
}
给定一个节点数为n的无序单链表,对其按升序排序。
思路:将链表中的值放到一个动态数组中
定义指针P
循环遍历后 重新指向head,在将数组中的值依次放到链表中
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类 the head node
* @return ListNode类
*/
ListNode* sortInList(ListNode* head) {
// write code here
vector<int>AA;
ListNode *p = head;
while(p)
{
AA.push_back(p->val);
p = p->next;
}
sort(AA.begin(),AA.end());
int i =0;
p = head;
while (p) {
p->val = AA[i];
p = p->next;
i++;
}
return head;
}
};
删除链表中的重复元素
思路:该题是带头节点的 ,定义临时指针指向头节点 开始时先判断头节点是否为空,然后通过头节点后的第一个有效节点开始遍历 当有值相等时,cur->next = cur->next->next;删除节点即可,
否则继续遍历即可,最后返回头节点
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head==nullptr)
{
return head;
}
ListNode *cur = head;
// 头节点不存放有效元素
while(cur->next)
{
if(cur->val == cur->next->val)
{
cur->next = cur->next->next;
}else
{
cur = cur->next;
}
}
return head;
}
};
各位相加
给定一个非负整数 num
,反复将各个位上的数字相加,直到结果为一位数。返回这个结果。
思路 定义临时变量 sum 反复的取模10 再÷10 , 结果给到num 一重循环判断是否>=10
二重循环判断num >0;
class Solution {
public:
int addDigits(int num) {
while(num>=10)
{
int sum =0 ;
while(num >0)
{
sum += num %10;
num = num /10;
}
num = sum;
}
return num;
}
};