编程入门:数字反转、字符统计与素数判断算法精解

回文数统计:从基础判断到区间遍历的算法详解与Python实现 回文数是编程算法中的经典概念,指正读反读都相同的数字或字符串。其核心原理在于对称性,可通过字符串反转或数学取模运算进行判断。掌握回文数处理不仅能提升基础编程能力,更是理解循环控制、条件分支和整数位操作的绝佳实践。在算法优化层面,从暴力遍历到生成构造法的演进,体现了时间复杂度分析的重要性。本文以Python为例,深入讲解如何高效统计指定区间内的回文数个数,涵盖字符串切片与数学运算两种实现方案,并针对边界条件、测试用例设计等工程实践中的常见问题提供解决方案。 阅读详情

1. 项目概述

东华OJ基础7-9题是面向编程初学者设计的经典算法练习题集,主要考察基础编程能力和逻辑思维。这三道题目难度适中,非常适合刚接触算法竞赛的同学作为入门训练。我在指导学生备战各类编程竞赛时,发现很多同学都会在这个阶段的题目上遇到瓶颈,主要问题往往不在于语法本身,而是缺乏系统化的解题思路。

这三道题目虽然被归类为"基础题",但实际包含了数组处理、字符串操作、数学运算等核心编程概念。掌握这些题目的解法,不仅能帮助初学者建立信心,更能为后续学习动态规划、图论等高级算法打下坚实基础。下面我将从题目解析、算法思路、代码实现到优化技巧,全方位拆解这套经典练习题。

2. 题目解析与算法设计

2.1 第7题:数字反转

这道题要求将一个整数各位数字反转后输出。看似简单,但需要考虑以下几个关键点:

  1. 如何处理负数情况
  2. 反转后前导零的处理
  3. 数值范围溢出问题(特别是32位有符号整数)

核心算法 :通过循环取模运算逐位提取数字。具体步骤:

  1. 初始化结果为0
  2. 当原数不为0时循环:
    • 取原数最后一位(num % 10)
    • 结果值乘以10后加上这位数
    • 原数去掉最后一位(num /= 10)
  3. 处理符号位

注意:必须检查反转后的数值是否超出32位有符号整数范围[-2³¹, 2³¹-1],这是该题最容易忽略的边界条件。

2.2 第8题:字符串统计

题目要求统计给定字符串中字母、数字、空格和其他字符的数量。这道题考察的是:

  1. 字符串遍历方法
  2. 字符分类判断
  3. 高效统计技巧

优化技巧 :

  • 使用字符ASCII码范围判断比直接比较更高效
  • 预先定义分类标准:
    • 数字:48-57
    • 大写字母:65-90
    • 小写字母:97-122
    • 空格:32

常见错误 :

  1. 忽略字符串可能包含中文等Unicode字符
  2. 未考虑字符串为空的情况
  3. 统计时类型转换错误

2.3 第9题:素数判断

判断给定整数是否为素数的经

GESP四级解析|绝对素数 第2集 GESP四级C++样题卷编程题第一题:绝对素数解析 如果一个两位数是素数,且它的数字位置经过对换后仍为素数,则称为绝对素数,例如 $13$。给定两个正整数 $A, B$,请求出大于等于 $A$、小于等于 $B$ 的所有绝对素数。 阅读详情

相关推荐

Python编程入门:100道实战练习题巩固基础语法与算法思维

编程语言学习的关键在于将理论知识转化为实践能力,而Python作为一门简洁高效的通用语言,其基础语法和算法思维是构建编程能力的核心。通过系统性的练习,开发者可以深入理解变量、函数、流程控制等基础概念,掌握数据结构与算法的实现原理,从而提升代码编写效率和问题解决能力。这种训练方式尤其适用于数据处理、文本分析和自动化脚本等常见应用场景。本文聚焦于一套包含100道题目的Python编程练习集,它覆盖了从基础语法到文件操作、算法实现的完整知识体系,通过分类题型解析和调试技巧,帮助初学者快速建立编程手感,实现从知道到

weixin_30706691的博客 359

题解:洛谷 B2136 素数回文数的个数

等知名刷题平台精心挑选而来,并结合各平台提供的算法标签和难度等级进行了系统分类。题目涵盖了从基础到进阶的多种算法和数据结构,旨在为不同阶段的编程学习者提供一条清晰、平稳的学习提升路径。),既是素数又是回文数的整数有多少个。之间的素数回文数个数。本文分享的必刷题目是从。#入门# #语法基础#

团爸讲算法 851

MLX90640 热成像 STM32

MLX90640 热成像

zhaocundang's blog 5008

`全网最细!! 入门必看Git教程链接:https://gitee.com/all-about-git`

全网 Git 入门教程 gitee.com。如果显示The requested URL returned error: 403错误,那就表示没有和window本地建立token令牌

qq_37855368的博客 3749

从RTL到GDSII:DC综合里那些没人告诉你的时钟约束冷知识(附真实工程示例)

本文深入探讨数字IC设计中DC综合阶段的时钟约束冷知识,包括无毛刺时钟切换、寄存器分频时钟约束、虚拟时钟应用等关键技巧。通过真实工程示例,揭示常见约束误区及解决方案,帮助工程师提升时序收敛效率。特别针对input_delay和output_delay在多时钟域场景下的设置陷阱提供实用指南。

weixin_29306317的博客 431

Coze智能体开发:如何搭建一个生成长文本的工作流

扣子工作流提供了流程定制化的能力,我们可以把长文生成的流程拆分为多个步骤,例如先通过大模型节点生成大纲、再使用循环节点依次扩写各个段落,最后将各个段落组合起来,从而实现长文生成流程。此工作流可适用于学术写作、商业报告、小说创作等多种场景。

王国平的博客 1792

25 - GRACE Mascon数据缺失月份数据插值

本篇基于文章的相关内容和文章公开的奇异谱分析(SSA)插值算法程序包,对grace Mascon数据种缺失的月份进行 插值 ,总结了使用程序包的相关过程,可以将该程序应用到其他数据处理插值计算中。

weixin_43339605的博客 1843

合肥工业大学操作系统实验8

依据操作系统课程所介绍的地址映射与内存共享的原理,本实验的目的是深入理解物理内存的分页管理方式。 深入理解操作系统的段、页式内存管理。包括理解段表、二级页表,以及逻辑地址、线性地址、 物理地址的映射过程。编程实现段、页式内存管理上的内存共享,从而深入理解操作系统的内存管理。从而加深对教材上地址映射与内存共享的理解。

Martin-share的博客 1721

【K210+STM32项目】基于K210与STM32协同工作的智能垃圾分类系统设计与实现(更新3.0版本)(完整工程资料源码)

STM32F407STM32F407_2(含有app功能)

嵌入式技术开发 2498

【C2000系列DSP的堆栈评估方法】程序跑飞,如何快速定位是否堆栈溢出?

静态分析:通过 CCS 编译器快速获取理论堆栈使用量,适合初步评估,无法覆盖动态场景; RAM 填充法:最可靠的动态评估方法,通过填充特征值检测实际最大堆栈使用量,需覆盖所有运行场景; 调试器监控:调试阶段快速验证堆栈指针变化,辅助确认关键函数 / 中断的堆栈占用。

昔时扬尘处 236

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

上一篇: 基于ThinkPHP与Laravel的校园快递代取系统开发实践
下一篇: MOF晶体结构获取指南:从CCDC数据库免费下载CIF文件
java2000_test
博客等级 码龄19年 10粉丝 320原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值