A Small Project: Splitting An Integer Into Digits

free web hosting
Free Web Hosting > Computers & Tech > Programming > Programming General > BASIC / Visual Basic (.NET)

A Small Project: Splitting An Integer Into Digits

derouge
I need to know how to "split" a number up into seperae numbers, using VB. For example, "54321". I need to split that into 5 seperate numbers - "5," "4," "3," "2," "1," and assign them to a variable, if possible.

This next part isn't important, but if you're curious why I need to know ...
Eventually what I need to do is split the number into these individual parts and add them together. With that new number I need to again split it and take the last number subtracted from 10. That new number will then be placed at the end of the beginning number.

Example:
5+4+3+2+1 = 15
15 = 1 & 5, take the last number ..
10-5 = 5
New number = "543215"

The thing is I have no clue how to split this number into the seperate parts. Once I get past that I'm 99% sure I can wrap up. Anyone able to help? If so, Thanks! smile.gif

Reply

miCRoSCoPiC^eaRthLinG
That should be fairly easy with the String manipulation routines that accompany VB. There are infact two methods you can follow.

Method 1:
    [/tab]To start with, you can simple convert the number into a string - and then use the substring function to find out each character. To achieve this we'll have to find the length of the string - which is 5, in your example above - and then iterate through each position of the string, picking up individual characters as we go.
CODE

'Say my number is stored in a variable called Num
Dim Num As Integer = 54321

'First I declare two variables - actually one Array to hold each character
'We just assing a random number of elements to the array - having 32
'will help us deal with numbers as long as 32 digits long
Dim Digits (32) As Integer

'And one variable to hold the length of the string
Dim Length As Integer

'I convert it to a String first
Dim NumString As String = CType ( Num, String )

'This NULL-Check is implemented so that if you use an empty string here, the code
'won't crash when it comes to checking for the substring - but instead would
'gracefully skip this part altogether
If NumString <> "" Then
 
   'Now I find the length of the string -  
   Length = NumString.Length

   'Iterate through the string, picking up each character
   For Index As Integer = 0 To Length - 1
       Digits ( Index ) = CType ( NumString.SubString ( Index, 1 ), Integer )
   Next

End If


That's it - the above approach will give you an array called Digits() whose positions indexed by 0 through Length - 1 will contain the individual digits of your number.

[hr=noshade][/hr]
Method 2:
[tab]The second method essentially involves the same principle as above - but computationally is a little faster - as the algorithm is based on numerical computations. A few words on the algorithm first.

    [/tab]Take for example, your own number, 54321 - can you think of a concrete method of stripping the number off the first digit "5" - leaving behind only "4321" ??
What would give you 5 as a result, if you divide 54321 by it ? You'd instantly arrive on the figure 10,000.
So: 54321 / 10000 = 5
This is all fine - you've got your first digit. But then how do you get the rest of the number together ? Arithmatically, if you divide 54321 by 10000 - we'd have a remainder of 4321 - that's exactly what we need. So how do you find the remainder. Here's where an arithmatic operator called Mod comes into play. It's known as Mod in terms of Visual Basic - and mostly represented as a % symbol in languages like C/C++, Java etc.
So: 54321 Mod 10000 = 4321

There - we have our first digit extracted, leaving behind the last four. Now if you repeat the above steps, except that you divide and do the Mod with 1,000 instead of 10,000 - you'd yet extract one more digit leaving behind the last 3. Next you repeat the steps again with 100 and then with 10 - and you'd have all your digits separated out.

How do we implement this ? Here's the code:
CODE

'Say Num contains the number
Dim Num As Integer = 54321

'Once again - we find the length of the number - which gives us the number of
'digits in it, and then we declare an array based on that number
Dim Length As Integer
If Str ( Num ) <> "" Then
   Length = Str ( Num ).Length
End If

'Next we declare two variables and an array
Dim Divisor As Integer = 10 ^ ( Length - 1 )
Dim Index As Integer = 0
Dim Digits ( Length - 1 ) As Integer

'Here we start the Loop
While ( Divisor > 0 )
   
   'Extract the first digit
   Digits ( Index ) = Int ( Num / Divisor )
   
   'Extract remainder number - and store it back in Num
   Num = Num Mod Divisor

   'Decrease Divisor's value by 1/10th units
   Divisor /= 10

   'Increment Index
   Index += 1

End While


Even in this case, your array Digits() will contain the extracted digits starting from position 0 through Length - 1.

[tab]Try out both and let me know - both should work just fine, giving your the same output. Personally, I find the second method more ELEGANT. The first one is a little blunt - doing things by brute force, although is much easier to understand. However, as I mentioned earlier, the second one computes way faster.

All the best smile.gif
m^e

 

 

 


Reply

hatim
Well it would be relevant if you posted which language you wanted this solution for. I think converting a number into string and then converting into numbers again is an easy solution. In C++ probably the shift operatros would do the trick.

Reply

miCRoSCoPiC^eaRthLinG
Oh yeah - that reminds me, since you made the post in VB.NET forum - the solution provided was in that same language too.

Also hatim - if you notice the solution I provided in Method 1 does exactly the same - conversion to string, extraction and then back to integer - and the second method entirely eliminates the need to do that, thus making the algorithm far more efficient.

Reply

derouge
Since I hate to leave people hanging ..

I went with the second method, and it works excellent! Much thanks. smile.gif

Reply

miCRoSCoPiC^eaRthLinG
Awesome. Glad that helped smile.gif That second method was a chance discovery while I was experimenting with coding a bunch of numerical manipulations quite sometime back - in relation to this cryptographic routine that I was trying to come up with.

Reply


Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.

Recent Queries:-
  1. getting separate numbers of an integer java - 0.91 hr back. (1)
  2. splitting an integer into numbers - 2.37 hr back. (1)
  3. first digit of integer - 4.32 hr back. (1)
  4. how the number into its individual digits in vb? - 7.40 hr back. (2)
  5. java splitting up int into digits - 11.74 hr back. (1)
  6. express integers in terms of its individual digits - 35.93 hr back. (1)
  7. java split an int into its digits - 38.63 hr back. (1)
  8. integer digits - 38.81 hr back. (1)
  9. visual basic, enter in 5 number, split them into individual value - 40.68 hr back. (2)
  10. java get first 10 digits - 41.08 hr back. (1)
  11. separate digits in integer - 42.54 hr back. (1)
  12. extract integer from four digit integer - 42.60 hr back. (1)
  13. seperate number into digits in c - 44.02 hr back. (1)
  14. how to split number into integers - 45.06 hr back. (1)
Similar Topics

Keywords : small, project, splitting, integer, digits

  1. A Small (?) Suggestion.
    (5)
  2. Project Virgle
    (8)
    Google is looking for people to participate in Project Virgle, which will establish a permanent
    human colony on Mars in 2014. A long-term plan has been put in place, however this may change with
    further information: http://google.com/virgle/plan_1.html . To apply as a participant, you need to
    fill out the questionnaire on this page: http://google.com/virgle/application.html . You must also
    submit a YouTube video of why you want to live on Mars here: http://youtube.com/projectvirgle .
    This planet will become open-source, as described here http://google.com/virgle/op....
  3. Small And Big Characters (a & A)
    (11)
    Hey! Is there anyway to make the following: Mysql don't care if the users character is
    small or big. If I type Feelay instead of feelay, in my message when I want to write to myself,
    mysql thinks that I wrote to someone else. I want to be able to write both Feelay and feelay and
    send to the same user. Is that possible? This is the code I am using atm: CODE
    /*if($user['to_user'] != $userfinal){ die("You are
    trying to view another users posts! Thats impossible!"); }*/ (I have made it as
    a c....
  4. Small Problem With My Domain.
    (3)
    Okay, so here is what happened: I started my site using sonic-deck.uni.cc as the domain name,
    assuming I shouldn't prefix it with a www. , however this means that mediawiki which I have
    installed always goes to sonic-deck.uni.cc and the rest goes to www.sonic-deck.uni.cc, I believe
    this can be fixed. I tried rewriterules and redirects but it didn't work. So, could you please
    switch my domain to www.sonic-deck.uni.cc server-wise? EDIT: I've fixed the problem with
    mediawiki by adding changing the $wgServer variable to my site's url. Although it would....
  5. Setting Up Your Php Server
    a small introduction on server setup. (0)
    Everyone who wants to practice PHP cant begin just by opening up notepad>Type php codes>Saving it
    as.php then viewing . No it wont work. Infact, your browser wont recognize it as "it doesnot have
    the knowledge of php" You can always setup a localhost server where you test your files
    offline/online on your computer directly. OR You can always setup a globalhost server where you find
    a host supporting PHP. Features that you should look for in a host: -CronJobs(optional but usually
    recommended) : Cron Jobs are scripts processed at set intervals of time. Suppose on a php m....
  6. A Team Effort For A Project
    (6)
    Hey guys, Im currently a one man army at the moment and well my game is progressing very slow as
    its taking me for ever to create I've done alot of the site how ever but in comparison to how
    much is left its not..... So was wondering if any one would like to help out...a team would be
    nice, slightly more enjoyable too in terms of creating a project right up to completion I was one
    working with a team and I much prefer that to doing it solo. My game isn't built for profit
    making so i cannot pay you before you ask. I'm making this site as a hobby and a lea....
  7. Basics Of Php For Beginners - Suggestion
    Help Needed For Project (5)
    Hi all, I have a friend who, for his extended IT project is interested in making a website partly
    out of php. When he asked for advice my first thought was here. I would like to know some good
    websites, tutorials etc that he can use to introduce himself to php (he hasn't done much
    before). He is interested in making a simple login/subscription service where you can signup and
    then login to a 'members only' page. Any ideas and code samples that you have to share would
    be greatly appreciated. /tongue.gif" style="vertical-align:middle" emoid=":P" border="0" a....
  8. Web Standard Project
    (3)
    Hello every one, It is always said that our websites should comply with w3c standard and should be
    xhtml/css compatible but the browsers usually don't suppport the standardized thing effectively
    and you usually have to go against standards to get things done. Don't know why w3c don't
    ask these people. Regards Haris....
  9. Gizmo Project
    (0)
    Contrary to public opinion, not all Americans have cell phones. For those of us who want freedom
    from paying high long distance bills, there is Gizmo Project. Gizmo Project is a light application
    used on your desktop and is useful as a VOIP phone, but with cost can dial landlines and wireless
    phones and vice versa. After downloading, it places itself on the desktop everytime after startup.
    Hence it is always ready should you need to make a long distance call. The Home page is where
    you choose either Call Out or Call In numbers. For 3 months at a cost of $1....
  10. Linux Partitioning With Ntfs
    Splitting a partition (4)
    Because of this topic , I have decided to download and try Ubuntu myself. I used BitTorrent to get
    the ISO image, wasted a CD-R to burn the image on and then booted up the operating system. My first
    time using Linux. My first control of Linux. My first time using Firefox in Linux. Extremely
    exciting. Anyways, Linux looks cool and I want to use it with Windows XP. The CD in the drive was
    extremely hot when I took it out, I could also hear strange noises coming from the drive. I think it
    would be a better idea to actually install the operating system on the hard disk. ....
  11. Ajax+php+sql=simply Superb!(with Visitor Tracking) :: Section 2 (retrive Values From Database And Dynamic Update!)
    A small tutorial to explain integrating php, ajax and MySQL Database (2)
    Hi all.. This the Section 2 for my previous tutorial about storing values in background using
    ajax! Please have a look at here:
    Astahost.com/ajax-php-sql-simply-superb-visitor-tracking-t15502.html Introduction!
    We are going to create 2 background script files. One to get values from the main page input field
    and store all values including visitor details ( IP Address, Input Value, Visitor Agent etc) to
    database and the 2nd one for retrieving all values from database and display it in the screen!
    We are going to 2 separate pages first and the....
  12. Ajax + Php + Sql = Simply Superb! ( With Visitor Tracking )
    A small tutorial to explain integrating php, ajax and MySQL Database (10)
    Hi all.. I'm back with a new small tutorial! Introducation A tutorial to
    integrate Ajax, Php And Database ( Im using MySQL) + Visitor Tracking! Here you can enter
    values to some input fields, and by clicking some enter button, ( or u can call the function on some
    other event) those values will be sent to the database, along with visitor details ( IP Address,
    Input Value, Visitor Agent etc)! Those values will be stored in some database and you can
    retrieve the same using some simple php code and even deleted some rows from those databases&#....
  13. A Small Gallery
    (0)
    Ok well here is the gallery: I was messin around with size and blurred the left side to much:
    Here is one without text. I asked the ppl (not the person who it was for) for a review publicly
    without text so they wouldn't know who it was for: This one was for a challenge
    where I needed certain things in my sig: Here is a Video Tutorial I made (not my best):
    Click Here for the Tutorial ~ZoroSeerus a.k.a. Team Destiny07 /biggrin.gif"
    style="vertical-align:middle" emoid=":D" border="0" alt="biggrin.gif" />....
  14. Lousy Tech Support
    a small sampling (5)
    I post frequently regarding troubleshooting problems I run into, and one reason is because I
    can't find much decent help around. I've made reference on occasion to the lousy tech
    support available locally, but I just thought I'd show a sample of it. This is from the Sci-Tech
    world, a weekly addition to the newspaper. It's not entirely technical, but is one of the few in
    the country, and as such is referred to by a lot of people. It also represents the average technical
    knowledge of the guy at the computer store, if even. QUOTE QUESTION: I have a Penti....
  15. Gizmo Project
    Free or cheap VOIP phone (3)
    The latest release that you can download is Gizmo Project 2.0.3.235(Nov 2006) at
    www.gizmoproject.com Gizmo Project is either a free or cheap soft phone. Free for Gizmo Project
    to Gizmo Project callers or business callers and cheap ( 1 cents per minute) for Gizmo Call Out and
    35 dollars per year for Gizmo Call In. Call Out means you can call out to a regular telephone and
    Call In means a regular telephone can call in to you. Call Out works like a pre-paid phone. I
    downloaded Gizmo Project onto my computer in May and paid the minimum of $10.00. (I believe I
    pai....
  16. Programmers' Association: Project #1 - Download Warper
    The making of Download Warper (6)
    OK team, our first job would be to create a download manager named 'Download Warper'.
    Here's what we will need:- A custom Winsock class - This would ensure speed regulation
    mechanism. It will also aid in using multiple connections. HTTP Connection class - This would
    contain the Winsock class and would basically do all the protocol specific low level transactions.
    FTP Connection class - Similar to the above class except that this would be for the FTP protocol.
    Main Application - The GUI for the Download manager. Other Requirements:- Icons and other graphics.....
  17. A Small Prob In Winamp
    (2)
    while im trying to open audio files.....im facing a prob with enqueue... the optioin
    "enque in winamp" is not working.... and my winamp is closing with an error...? can anyone solve
    this...? /smile.gif" style="vertical-align:middle" emoid=":)" border="0" alt="smile.gif" />....
  18. The Sum Of The Cubes Of The Digits Of Any Non-negative Integer
    (5)
    Ok I need someone to help me tackle this program. Here's the question: Exercise 9 a) Write a
    program that displays the sum of the cubes of the digits of any non-negative integer. Two program
    runs are shown below: Enter an integer: 145 Sum of digits is 10
    Enter an integer: 8888 Sum of the cubes of the digits is 2048 /cool.gif"
    style="vertical-align:middle" emoid="B)" border="0" alt="cool.gif" /> Modify the program to
    determine what integers of two, three, or four digits are equal to the sum of the cubes of their
    digit....
  19. CSS Project (in Progress)
    (3)
    http://www.trap17.com/forums/index.php?sho...mp;#entry297172 this is also on trap but would like
    some input from asta as well you can see the live version here
    http://saint-michael.trap17.com/css/index.html Two problems i would like to work on next is fix
    the overlapping in IE7. Basically the content is above the header. Next is my left/right column
    nav menus for some reason they are going behind the divs below. Although I haven't tried it yet
    but I would think setting up a container element would fix this would I be correct on this
    assumption? latest code ....
  20. Checking To See If Something Is Not An Integer
    (4)
    I put together this: CODE //Make Sure $qty is NOT blank before checking if it is a number
        if (!empty($item_1_qty)) { //not empty             }     if
    (intval($item_1_qty) !== $item_1_qty){             //item 1 qty is not
    a whole number             $redirect_to = 'order_form.php?error=6';    
                header("Location: $redirect_to");             exit();
            } But I get my error message coming no matter whether it is an integer or not.....
  21. Splitting A Long Video Into Small Pieces For Youtube.
    (7)
    I have a long (20 minutes) video encoded in MPEG2 (I believe), and weighing about 1.3GB. If
    you're interested, it is the footage from a big concert in which my band performed at the
    beginning of this month. I want to first of all, split all the different songs into different files,
    and then upload them to Youtube or a similar site so as to prevent myself from having to send out
    huge files in many directions. I've tried many different programs. Windows Movie Maker keeps
    freezing when I "import" the video into it, probably because it is not used to such large file....
  22. How To Use Rss Feeds!
    A small tutorial on RSS feeds usage! (1)
    Original Post here: http://www.fun.niranvv.com/viewtopic.php?t=632 Hi all. RSS feeds are the new
    trends in the Information Technology Field! What IS RSS: RSS is a protocol, an application
    of XML, that provides an open method of syndicating and aggregating Web content. Using RSS files,
    you can create a data feed that supplies headlines, links, and article summaries from your Web site.
    Users can have constantly updated content from web sites delivered to them via a news aggregator, a
    piece of software specifically tailored to receive these types of feeds. M....
  23. What Do This Code In Assembler.
    A small piece of code can do magic. (3)
    The following source code was a self-challenge to see if i could program such algorythm in assembler
    and generate the smallest file possible that keeps the functionality of my program. This is sort of
    minimalistic programming. Here is the code. It generates a 432byte length .COM executable file that
    needs to run from command line at full screen (uses graphic resources). So, what is this program
    for?, do you dare to give an answer? CODE ;To assemble, use A86 assembler under DOS/WIN
    machine. It generates a 432 byte COM executable.         SCRX    equ LOOP1-2       ....
  24. Project Revolution [w3 -> Sc]
    Warcraft 3 to Starcraft Total Conversion (1)
    I proudly present Project Revolution. You can visit their website here . Project Revolution
    basically consists on creating a high-fidelity and high-quality Starcraft game using current
    Warcraft III engine (what's really hard, but believe me, the staff rocks). They got featured on
    a PC Gamer magazine as you guys can see here , and a note in the front cover! It's a damn
    good mod after all, and once it's done it'll proportionate hours and hours of fun to
    millions of fans worldwide. So, spread out the word and let everyone know! PS.: I don't....
  25. XP Problem: Clicking On Folder Opens Search
    (4)
    I have no idea why, but for some reason whenever I click on a folder now it opens it as a search
    instead of just showing me the contents. Whenever I right click it, search is at the top of the tab
    in bold instead of open. Is there any way I can fix this? I have no idea what I did wrong. Sorry,
    I fixxed it.....
  26. Dogs Trained To Detect CD & DVD At Airports
    Movie industry finance the project (13)
    Movie's Industry financed dog's training to detect huge CD & DVD quantities. The two first
    animals trained to identify this type of mesures are already working in Stansted Aeroport, England.
    The dogs, Lucky and Flo are capable to recognize the smells from CD and DVD and point the suspect
    packages. The dogs training was payed by MPAA ((Motion Picture Association of America) and for
    FACT (Federation Against Copyright Theft). Dog's are used to identify bomb's, drugs in
    aeroports, but this is a first time that they are used to act in Copyright programs co....
  27. Decrementing Number Of Digits Ofter Point
    In C# (15)
    Hi! I've been solving a problem on C# and a one problem had gone off. I need to decrease
    number of digits of a float variable. for example: If I have 14.3413543485 I wanna make it just
    14.34. My Informatic teacher says there is a way, but he'd forgot it. Could you, please, help
    me?....
  28. Paint.NET Project - A Free Picture Editor
    replace your standard microsoft paint! (2)
    Hello designers! This little piece of software will get you change your thoughts about
    microsoft's Paint software. A few students made this software under direct influence of
    microsoft. It's a derivate from ms Paint, but it has many many more functions available. You
    might not notice that functions at first but let me assire you, you will see that it has some of
    stuff that you didn't expect. Ok, so enough talk, here is a screenshoot: And one more great
    news related to this, it's a freeware, and you can even download for free - source code, and se....
  29. Windows XP Small Tips (Chap One)
    (2)
    Windows XP small tips! /laugh.gif' border='0' style='vertical-align:middle' alt='laugh.gif' />
    1- to take a photo from your screen press Print Screen button, and then paste in an image editor.
    2- to take an image from movies in Windows Media Player press Ctrl+I and then save. 3- To change
    your file extensions open folder option and go to view tab and select Hide extensions for known
    file types. Now you can change file extensions. Note: do not change system file extensions 4- to
    Scan and verify the versions of all protected system files type sfc /scannow in Ru....
  30. The Best Mmorpgs You've Ever Tried!
    Ragnarok Online, Survival Project, etc. (31)
    Well, I've tried some MMORPGs here at Indonesia, and here's my reviews about them: RAGNAROK
    ONLINE ============= This is the first MMORPG I've ever played, and I'm still playing it
    'til now. IMHO, this is the best MMORPG among the others, because it has a wide range of
    community and the game itself is still being developed by Gravity of Korea, the maker of this game.
    Well, I haven't tried Final Fantasy XI, which is said to be the best MMORPG out there, but
    certainly, you can count Ragnarok Online is one of the most popular MMORPG throughout the....

    1. Looking for small, project, splitting, integer, digits

*RANDOM STUFF*





*SIMILAR VIDEOS*
Searching Video's for small, project, splitting, integer, digits
Similar
A Small (?) Suggestion.
Project Virgle
Small And Big Characters (a & A)
Small Problem With My Domain.
Setting Up Your Php Server - a small introduction on server setup.
A Team Effort For A Project
Basics Of Php For Beginners - Suggestion - Help Needed For Project
Web Standard Project
Gizmo Project
Linux Partitioning With Ntfs - Splitting a partition
Ajax+php+sql=simply Superb!(with Visitor Tracking) :: Section 2 (retrive Values From Database And Dynamic Update!) - A small tutorial to explain integrating php, ajax and MySQL Database
Ajax + Php + Sql = Simply Superb! ( With Visitor Tracking ) - A small tutorial to explain integrating php, ajax and MySQL Database
A Small Gallery
Lousy Tech Support - a small sampling
Gizmo Project - Free or cheap VOIP phone
Programmers' Association: Project #1 - Download Warper - The making of Download Warper
A Small Prob In Winamp
The Sum Of The Cubes Of The Digits Of Any Non-negative Integer
CSS Project (in Progress)
Checking To See If Something Is Not An Integer
Splitting A Long Video Into Small Pieces For Youtube.
How To Use Rss Feeds! - A small tutorial on RSS feeds usage!
What Do This Code In Assembler. - A small piece of code can do magic.
Project Revolution [w3 -> Sc] - Warcraft 3 to Starcraft Total Conversion
XP Problem: Clicking On Folder Opens Search
Dogs Trained To Detect CD & DVD At Airports - Movie industry finance the project
Decrementing Number Of Digits Ofter Point - In C#
Paint.NET Project - A Free Picture Editor - replace your standard microsoft paint!
Windows XP Small Tips (Chap One)
The Best Mmorpgs You've Ever Tried! - Ragnarok Online, Survival Project, etc.
advertisement




A Small Project: Splitting An Integer Into Digits



 

 

 

 

ADD REPLY / Got an Opinion! a humble request :-) RAPID SEARCH! Free Hosting [X]
Express your Opinions, Thoughts or Contribute your information that might help someone here.
Ask your Doubts & Queries to get answers.. "Together, We enlight each other!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE