Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize bit addition in C # algorithm

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

In this article, the editor introduces in detail "how to add you in the C# algorithm". The content is detailed, the steps are clear, and the details are handled properly. I hope this article "how to add you in the C# algorithm" can help you solve your doubts. Let's follow the editor's ideas to slowly deepen, let's learn new knowledge.

Add up, everyone.

Given a non-negative integer num, the numbers in each bit are added repeatedly until the result is a single digit.

Example:

Input: 38 output: 2 explanation: the process of adding you is: 3 + 8 = 11, 1 + 1 = 2. Because 2 is a single digit, 2 is returned.

Advanced:

Can you solve this problem within O (1) time complexity without using loops or recursion?

Code template public class Solution {public int AddDigits (int num) {}}

test data

Input 1 output 1 input 10 output 1 input 38 output 2 input 1999output 1 input 8888 output 5 author's method:

The while loop is used, except for one calculation at a time, the original number and digits and change at the same time. The time is in 70ms.

Public static int Csum (int num) {if (num)

< 10) //小于10的数直接返回 return num; int shi = 0; //记录个位数相加 while (num >

0) {if (num > = 10) {shi + = num% 10; num = num / 10;} else if (num

< 10) { shi += num; num = num / 10; } if (shi >

= 10) shi = shi% 10 + shi / 10; / / re-change of the number of digits exceeding 10} return shi;} method two discard nine-check algorithm

Also at 60-70ms

Public class Solution {public int AddDigits (int num) {if (num==0) return 0; if (num%9==0) return 9; return num%9 }} after reading this, the article "how to add all of you in the C# algorithm" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report